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

查看:1006
本文介绍了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);
});

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

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