我有带有实体框架的 .NET Core 6 Web 应用程序。
我的 DbContext 是这样的:
public class MyDbContext : DbContext
{
public MyDbContextDbContext(DbContextOptions<MyDbContext> options) : base(options)
{
this.HasCustomFeature = // How to set it from configuration options
}
...
}
使用时如何通过配置选项传递
HasCustomFeature
:
services.AddDbContext<Model.MyDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
...所以我可以在构造函数中读取它?一般来说,
HasCustomFeature
设置值来自我的 DbContext 外部的应用程序选项。
可能最简单的选择是添加另一个 ctor 参数并在 DI 中注册相应的服务:
public class MyCustomOptions
{
public bool HasCustomFeature { get; set; }
}
public class MyDbContext : DbContext
{
public MyDbContext(DbContextOptions<MyDbContext> opts, MyCustomOptions myOpts):base(opts)
{
this.HasCustomFeature = myOpts.HasCustomFeature;
}
}
以及报名:
// sample registration, can be bound from config, etc.
serviceCollection.AddSingleton(new MyCustomOptions
{
HasCustomFeature = true
});
services.AddDbContext<Model.MyDbContext>(...);