I'm developing an ASP.NET Core 2.0.2 Web API with C# and .NET Framework 4.7.
I want to get the connection string from appsettings.json
in a method's controller.
I did it in Startup.cs:
using Microsoft.Extensions.Configuration;
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddDbContext<MyContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MyContext")));
[ ... ]
}
But I don't know how to do it in a controller. I have found this tutorial, Configure an ASP.NET Core App, but it uses a class to access configuration's options, public class MyOptions
I have tried to do it like in Startup.cs
, Configuration.GetConnectionString("MyContext")
, but it doesn't recognize Configuration
class.
My question is:
How can I get the connection string in a controller?
You may directly inject IConfiguration configuration
into your controller (it is registered in DI container by default) :
// using Microsoft.Extensions.Configuration;
public class YourController : Controller
{
public YourController (IConfiguration configuration)
{
var connString = Configuration.GetConnectionString("MyContext");
}
}
But anyway consider using the IOptions pattern as it will be more flexible.
public class MyOptions
{
public string ConnString { get; set; }
}
public void ConfigureServices(IServiceCollection services)
{
// Adds services required for using options.
services.AddOptions();
services.Configure<MyOptions>(myOptions =>
{
myOptions.ConnString = Configuration.GetConnectionString("MyContext");
});
...
}
then
public YourController ((IOptions<MyOptions> optionsAccessor)
{
var connString = optionsAccessor.Value.ConnString;
}
You can inject IConfiguration
itself into your controller and get connection string:
public class HomeController : Controller {
private readonly string _connectionString;
public HomeController(IConfiguration config) {
_connectionString = config.GetConnectionString("MyContext");
}
}
you don't need your connectionstring, you've already prepared to inject your dbcontext. So you can basicly just inject your dbcontext. (don't do this in your controller, and seperate this, and create a repository or something and inject this).
you need to add 1 extra injection in your startup:
services.AddScoped<IDataContext, DataContext>();
where you context should look something like:
public class DataContext : DbContext, IDataContext
{
public DbSet<User> Users { get; set; }
public DataContext(DbContextOptions options) : base(options)
{
}
}
so then you can inject your context everywhere.
Perhaps this is not the answer you are looking for. In that case, you can add a model and bind this in your configuration and inject your model
something like:
services.Configure<AssetProviderServiceClientConfig>(
Configuration.GetSection("AssetProviderServiceClient"));
then you can inject your options like
private readonly SchedulerConfig _config;
public YourController(IOptions<SchedulerConfig> config)
{
_config = config.Value;
}
cheers!
EDIT:
execute SP;
if your context is injected you can do something like:
var command = databaseContext.database.GetDbConnection().CreateCommand();
cmd.CommandText = "your SP";
cmd.CommandType = CommandType.StoredProcedure;
using (var reader = cmd.ExecuteReader())
{
var entitites = reader.MapToList<Entity>();
}
perhaps there are some lines incorrect... Out of memory :)
you can use DbContextDatabase.GetDbConnection().ConnectionString get specified context connection string, like this
public HomeController(DbContext context)
{
var connectionString = context.Database.GetDbConnection().ConnectionString;
}
update:
or you can create delegate like
public delegate string ConnectionStringExporter();
then register it as
services.AddSingleton<ConnectionStringExporter>(() => Configuration.GetConnectionString("Default"));
in controller you can inject it as
public HomeController( ConnectionStringExporter exporter)
then you can get connectionstring with var connectionString = exporter();
you can also add the delegate paramter with specified connection string name. like public delegate string ConnectionStringExporter(string name);