我有一个ConfigurationDbContext
我正在尝试使用。它有多个参数,DbContextOptions
and ConfigurationStoreOptions
.
如何将此 DbContext 添加到 ASP.NET Core 中的服务中?
我在 Startup.cs 中尝试了以下操作:
ConfigureServices
....
services.AddDbContext<ConfigurationDbContext>(BuildDbContext(connString));
....
private ConfigurationDbContext BuildDbContext(string connString)
{
var builder = new DbContextOptionsBuilder<ConfigurationDbContext>();
builder.UseSqlServer(connString);
var options = builder.Options;
return new ConfigurationDbContext(options, new ConfigurationStoreOptions());
}
AddDbContext
执行 https://github.com/aspnet/EntityFrameworkCore/blob/master/src/EFCore/EntityFrameworkServiceCollectionExtensions.cs#L475只是在 DI 中注册上下文本身及其公共依赖项。
代替AddDbContext
调用,手动注册 DbContext 是完全合法的:
services.AddTransient<FooContext>();
此外,您可以使用工厂方法来传递参数(这正在回答问题):
services.AddTransient<FooContext>(provider =>
{
//resolve another classes from DI
var anyOtherClass = provider.GetService<AnyOtherClass>();
//pass any parameters
return new FooContext(foo, bar);
});
P.S.,一般来说,你不需要注册DbContextOptionsFactory
和默认的DbContextOptions
解析 DbContext 本身,但在特定情况下可能是必要的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)