ASP.NET Core IdentityDbContext使用依赖注入

时间:2016-05-29 17:27:45

标签: c# entity-framework dependency-injection asp.net-core asp.net-identity

在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>();

2 个答案:

答案 0 :(得分:1)

您真的不需要定义IApplicationDbContext以使依赖注入框架起作用。

你可以尝试

<强> Startup.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

答案 1 :(得分:0)

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

相反,您可以使用此语法,这将保留ApplicationDbContextAddDbContext内部注册services.AddTransient<IApplicationDbContext>(provider => provider.GetRequiredService<ApplicationDbContext>()); 的方式:

text.split(/\n\s*\n/)