简体   繁体   English

ASP.NET Core DbContext 注入

[英]ASP.NET Core DbContext injection

I have a ConfigurationDbContext that I am trying to use.我有一个我正在尝试使用的ConfigurationDbContext It has multiple parameters, DbContextOptions and ConfigurationStoreOptions .它有多个参数, DbContextOptionsConfigurationStoreOptions

How can I add this DbContext to my services in ASP.NET Core?如何将此 DbContext 添加到 ASP.NET Core 中的服务?

I have attempted the following in my Startup.cs:我在 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 implementation just registers the context itself and its common dependencies in DI. AddDbContext 实现只是在DI中注册上下文本身及其公共依赖项。 Instead of AddDbContext call, it's perfectly legal to manually register your DbContext: 而不是AddDbContext调用,手动注册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, In general, you don't have to register DbContextOptionsFactory and default DbContextOptions to resolve DbContext itself, but it could be necessary in specific cases. PS,通常,您不必注册DbContextOptionsFactory和默认DbContextOptions来解析DbContext本身,但在特定情况下可能是必要的。

You can use this in startup.cs. 您可以在startup.cs中使用它。

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

Detail Example : Getting started with ASP.NET Core MVC and Entity Framework Core 详细示例: ASP.NET Core MVC和Entity Framework Core入门

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

Try this for inject your ef context - context inheritance from IDbContext 试试这个注入你的ef上下文 - 来自IDbContext的上下文继承

1-Add your context to service: 1 - 将您的上下文添加到服务:

        public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<NopaDbContext>(
                        options => options
                        .UseLazyLoadingProxies()
                        .UseSqlServer(Configuration.GetConnectionString("NopaDbContext")),ServiceLifetime.Scoped);}

2-Inject your context: 2 - 注入您的上下文:

    private readonly IDbContext _context;

    public EfRepository(NopaDbContext context)
    {
        this._context = context;
    }

    protected virtual DbSet<TEntity> Entities
    {
        get
        {
            if (_entities == null)
                _entities = _context.Set<TEntity>();

            return _entities;
        }
    }

In order to register DbContext as a service in IServiceCollection you have two options:(we assume that you are going to connect to a SQL Server database) 为了在IServiceCollection DbContext注册为服务,您有两个选择:(我们假设您将连接到SQL Server数据库)

Using AddDbContext<> 使用AddDbContext <>

services.AddDbContext<YourDbContext>(o=>o.UseSqlServer(Your Connection String));

Using AddDbContextPool<> 使用AddDbContextPool <>

services.AddDbContextPool<YourDbContext>(o=>o.UseSqlServer(Your Connection String));

as you might see these two are in terms of writing have similarities, but in fact they have some fundamental differences in terms of concepts. 你可能会看到这两个在写作方面有相似之处,但实际上它们在概念方面有一些根本的区别。 @GabrielLuci has a nice response about the differences between these two: https://stackoverflow.com/a/48444206/1666800 @GabrielLuci对这两者之间的差异做出了很好的回应: https ://stackoverflow.com/a/48444206/1666800

Also note that you can store your connection string inside the appsettings.json file and simply read it using: Configuration.GetConnectionString("DefaultConnection") inside the ConfigureServices method in Startup.cs file. 另请注意,您可以将连接字符串存储在appsettings.json文件中,只需使用Startup.cs文件中ConfigureServices方法内的ConfigureServices Configuration.GetConnectionString("DefaultConnection")读取它。

You can put all your parameters of db context in a class AppDbContextParams and register a factory to create that object for appdbcontext: 您可以将db context的所有参数放在AppDbContextParams类中,并注册工厂以为appdbcontext创建该对象:

services.AddScoped(sp =>
            {
                var currentUser = sp.GetService<IHttpContextAccessor>()?.HttpContext?.User?.Identity?.Name;
                return new AppDbContextParams { GetCurrentUsernameCallback = () => currentUser ?? "n/a" };
            });

EF Core 6 / .NET 6 has some changes to make it easier (and supported) to register DbContext and DbContextPool at the same time for different usages. EF Core 6 / .NET 6 进行了一些更改,以便更容易(和支持)同时注册 DbContext 和 DbContextPool 以用于不同的用途。

https://docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-6.0/whatsnew#dbcontext-factory-improvements https://docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-6.0/whatsnew#dbcontext-factory-improvements

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM