问题描述
我有一个要使用的ConfigurationDbContext
.它具有多个参数DbContextOptions
和ConfigurationStoreOptions
.
I have a ConfigurationDbContext
that I am trying to use. It has multiple parameters, DbContextOptions
and ConfigurationStoreOptions
.
如何将此DbContext添加到ASP.NET Core中的服务中?
How can I add this DbContext to my services in ASP.NET Core?
我在Startup.cs中尝试了以下操作:
I have attempted the following in my 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
实现只是在DI中注册了上下文本身及其公共依赖项.代替AddDbContext
调用,手动注册DbContext是完全合法的:
AddDbContext
implementation just registers the context itself and its common dependencies in DI.Instead of AddDbContext
call, it's perfectly legal to manually register your DbContext:
services.AddTransient<FooContext>();
此外,您可以使用工厂方法来传递参数(这是在回答问题):
Moreover, you could use a factory method to pass parameters (this is answering the question):
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本身,但是在特定情况下可能是必需的.
P.S., In general, you don't have to register DbContextOptionsFactory
and default DbContextOptions
to resolve DbContext itself, but it could be necessary in specific cases.
这篇关于ASP.NET Core DbContext注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!