在多层项目中注入 ApplicationDbContext 以在 Aspnet Core Identity 中使用
Injecting ApplicationDbContext to use in Aspnet Core Identity in multilayer project
我有一个多层架构的 c# 项目,我不想从 Presentation 添加对我的 DAL 层的引用,所以我需要在 运行 时注入 ApplicationDbContext 以用于 Identity,对于这种方法我为此在业务层写了一个扩展方法。 (表示层参考了业务层)并在startup.cs中添加了如下方法:
public static IdentityBuilder AddDbContext(this IdentityBuilder builder, IServiceCollection services, string connStr)
{
services.AddTransient<ApplicationDbContext>(_ => new ApplicationDbContext(connStr));
builder.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
return builder;
}
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddDbContext(services, Configuration.GetConnectionString("DefaultConnection"));
services.AddMvc();
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
}
但是当我 运行 我的应用程序时,它在尝试 运行 时崩溃了。
错误页面如下:
我发现了问题,
其实问题不是因为 DI,而是因为我没有为我的 Domian 项目添加 using 指令到 _ViewImports.
我有一个多层架构的 c# 项目,我不想从 Presentation 添加对我的 DAL 层的引用,所以我需要在 运行 时注入 ApplicationDbContext 以用于 Identity,对于这种方法我为此在业务层写了一个扩展方法。 (表示层参考了业务层)并在startup.cs中添加了如下方法:
public static IdentityBuilder AddDbContext(this IdentityBuilder builder, IServiceCollection services, string connStr)
{
services.AddTransient<ApplicationDbContext>(_ => new ApplicationDbContext(connStr));
builder.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
return builder;
}
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddDbContext(services, Configuration.GetConnectionString("DefaultConnection"));
services.AddMvc();
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
}
但是当我 运行 我的应用程序时,它在尝试 运行 时崩溃了。
错误页面如下:
我发现了问题, 其实问题不是因为 DI,而是因为我没有为我的 Domian 项目添加 using 指令到 _ViewImports.