ASP.NET Core DbContext注入

blg*_*boy 8 c# entity-framework dependency-injection entity-framework-core asp.net-core

我有一个ConfigurationDbContext我想要使​​用的.它有多个参数,DbContextOptionsConfigurationStoreOptions.

如何将此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());
}
Run Code Online (Sandbox Code Playgroud)

Ily*_*kov 9

AddDbContext 实现只是在DI中注册上下文本身及其公共依赖项.而不是AddDbContext调用,手动注册DbContext是完全合法的:

services.AddTransient<FooContext>();
Run Code Online (Sandbox Code Playgroud)

此外,您可以使用工厂方法传递参数(这是回答问题):

services.AddTransient<FooContext>(provider =>
{
    //resolve another classes from DI
    var anyOtherClass = provider.GetService<AnyOtherClass>();

    //pass any parameters
    return new FooContext(foo, bar);
});
Run Code Online (Sandbox Code Playgroud)

PS,一般情况下,您不必注册DbContextOptionsFactory并默认DbContextOptions解析DbContext本身,但在特定情况下可能是必要的.


has*_*san 5

您可以在 startup.cs 中使用它。

详细信息:https : //docs.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext

详细示例:ASP.NET Core MVC 和 Entity Framework Core 入门

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddDbContext<ApplicationDbContext>(options =>options.
       UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
Run Code Online (Sandbox Code Playgroud)