【发布时间】:2019-06-21 12:09:39
【问题描述】:
我的 API 项目的 appsettings.json 中有我的连接字符串,我想在我的数据库项目的上下文中使用它。通常,依赖注入可以解决问题,但是,当我运行迁移时,我会收到此错误:
无法创建“上下文”类型的对象。对于不同的 设计时支持的模式,请参阅 https://go.microsoft.com/fwlink/?linkid=851728!
在上下文中硬编码连接字符串可以解决这个问题,但对我来说不是一个可行的解决方案,因为我需要根据环境更改连接字符串。请参阅 API 项目中的 ConfigureServices 方法和数据库项目中的上下文。
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed
// for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
services.AddDbContext<Context>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
public class Context : DbContext
{
private readonly IOptions<AppSettings> _settings;
public Context(IOptions<AppSettings> settings) : base()
{
_settings = settings;
}
public Context(IOptions<AppSettings> settings, DbContextOptions<Context> options) : base(options)
{
_settings = settings;
}
***DBSets***
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(_settings.Value.DBConnectionString);
}
}
【问题讨论】:
-
这是因为
_settings.Value.DBConnectionString没有得到连接字符串。 -
我知道这是问题所在,我在系统的其他部分使用了相同的技术,并且它在那里工作。
-
Startup类中将
optionsBuilder.UseSqlServer(_settings.Value.DBConnectionString);代码移动到ConfigureServices方法有问题吗?如果没有,我可以给出一个解决方案。 -
是的,这是一个问题,因为我必须在多个地方使用连接字符串初始化上下文,即我的测试项目。 OnConfiguring 方法中的解决方案将是最佳的。
标签: c# dependency-injection .net-core entity-framework-core