[英]Getting connection-string using Dependency Injection in OnConfiguring method in console application?
In a .NET Core Console Application I have the following DbContext: 在.NET Core控制台应用程序中,我具有以下DbContext:
public class AppDataContext : DbContext
{
public DbSet<ExampleObject> ExampleObjects { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseNpgsql(/* Read Connection String from appsettings.json */);
}
}
Of course I could instantiate the ConfigurationBuilder class and access the connectionString, like this: 当然,我可以实例化ConfigurationBuilder类并访问connectionString,如下所示:
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
Configuration = builder.Build();
var connString = Configuration.GetConnectionString("data"));
but how can I force Entity Framework to use the IConfigurationRoot instance defined with dependency injection? 但是如何强制实体框架使用通过依赖项注入定义的IConfigurationRoot实例?
Thank you 谢谢
You're approaching it from the wrong angle. 您正在从错误的角度接近它。 You're currently trying to "bring in" configuration.
您当前正在尝试“引入”配置。 What you need to be doing is "applying" the configuration at the ServiceCollection level so that the Net Core Dependency Injection can instantiate your DbContext with the correct values automatically.
您需要做的是在ServiceCollection级别“应用”配置,以便Net Core Dependency Injection可以自动使用正确的值实例化DbContext。 Here is an example of how to do that:
这是如何执行此操作的示例:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<BloggingContext>(options => options.UseSqlite("Data Source=blog.db"));
}
Of course you can still use the IConfigurationBuilder to get your connection string - that would go in the ConfigureServices section above and "Data Source=blog.db" would be swapped for your value 当然,您仍然可以使用IConfigurationBuilder来获取连接字符串-它将在上面的ConfigureServices部分中出现,并且“ Data Source = blog.db”将被交换为您的值
Your DbContext can then be simplified like this: 然后可以像下面这样简化您的DbContext:
public class AppDataContext : DbContext
{
public DbSet<ExampleObject> ExampleObjects { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.