ASP.NET Core DbContext 注入 [英] ASP.NET Core DbContext injection

查看:46
本文介绍了ASP.NET Core DbContext 注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我正在尝试使用的 ConfigurationDbContext.它有多个参数,DbContextOptionsConfigurationStoreOptions.

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);
});

PS,一般情况下,您不必注册 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 注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆