繁体   English   中英

使用依赖注入的 ASP.NET Core IdentityDbContext

[英]ASP.NET Core IdentityDbContext using dependency Injection

是否有可能在 ASP.NET Core 中使用新的依赖注入机制将 IdentityDbContext 注入我的存储库?

EF版本:

  "EntityFramework.Commands": "7.0.0-rc1-final",
  "Microsoft.AspNet.Identity.EntityFramework": "3.0.0-rc1-final", 

语境:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>,       IApplicationDbContext
{
    public DbSet<Customer> Customers{ get; set; }

    protected override void OnModelCreating(ModelBuilder builder) => base.OnModelCreating(builder);
}

存储库:

 public class CustomerRepository: ICustomerRepository
{
    private readonly IApplicationDbContext _context;

    public CustomerRepository(IApplicationDbContext context)
    {
        _context = context;
    }

    public List<Customer> GetAll()
    {
        return _context.Customers.ToList();
    }
}

如何配置 Startup.cs?

我有基本配置

        services.AddEntityFramework()
            .AddSqlServer()
            .AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

这不起作用:

        services.AddTransient<IApplicationDbContext, ApplicationDbContext>();

你真的不需要定义IApplicationDbContext来让依赖注入框架工作。

你可以试试

启动.cs

services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

    // You can actually use
    // Configuration.GetConnectionString("DefaultConnection") here instead to simplify the code

如果查看AddDbContext()的第二个参数, ServiceLifetime设置为Scoped ,这意味着对象实例在同一请求中将相同,但在不同请求之间不同。

如果你想让 DI 框架每次都创建不同的实例,你可以将第二个参数设置为Transient

存储库

public class CustomerRepository: ICustomerRepository
{
    private readonly ApplicationDbContext _context;

    public CustomerRepository(ApplicationDbContext context)
    {
        _context = context;
    }

    public List<Customer> GetAll()
    {
        return _context.Customers.ToList();
    }
}

DI 框架会自动为你注入ApplicationDbContext

使用services.AddTransient<IApplicationDbContext, ApplicationDbContext>(); 语法要求依赖注入块直接实例化ApplicationDbContext ,这绕过了 EntityFramework 设置的数据库上下文工厂。

相反,您可以使用此语法,这将保留ApplicationDbContext在内部注册的方式AddDbContext

services.AddTransient<IApplicationDbContext>(provider => provider.GetRequiredService<ApplicationDbContext>());

暂无
暂无

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

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