I develop a simple web app and, in the future, I want to do it as multi-tenancy.
So I want to write the connection string straight into OnConfiguring
method:
public class ApplicationContext : DbContext
{
public DbSet<User> Users { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("connection string from appsettings.json");
base.OnConfiguring(optionsBuilder);
}
}
Startup class:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationContext>();
services.AddMvc();
}
How can I extract connection string from appsettings.json
into ApplicationContext
class?
I wouldn't like to create any constructors for ApplicationContext
class.
You can use the factory pattern to resolve your
DbContext
.In Startup:
Your service or controller:
.NET Core 2.0
Add this class:
Get the value for the key "MssqlConnectionString" from the "appsettings.json" file:
Create the file "appsettings.json" in the root directory of your project:
Let's imagine that you have .NET Core application and your
appsettings.json
file looks like this:You can get
SqliteConnectionString
value fromStartup.cs
like this:And then in your
DBContext
you should add constructor that acceptsDbContextOptions
:You could use Options Pattern via
IOptions
but the easiest way is using DI inApplicationContext
constructor ;)Follow below articles, please: