[英]Is it possible to have DbContext in DAL in layered ASP.NET Core application?
例如,如果我有 3 層:
Data access layer -> Business Logic Layer -> Presentation Layer
考慮到我無法從表示層引用它,是否可以在 DAL 中使用DbContext
?
如果是,那么如果看不到DbContext
我如何在Startup.cs
使用 DB 進行初始化?
services.AddEntityFrameworkSqlServer()
.AddDbContext<DbContext>(options =>
{
...
});
我找到了我的問題的這種解決方案(考慮到人們在評論中幫助了我)我有一個帶有IServiceCollection
擴展方法的靜態類
public static IServiceCollection RegisterRepositories(this IServiceCollection services, IConfiguration configuration)
{
services.AddScoped(typeof(IRepository<>), typeof(BaseRepository<>));
services.AddScoped(typeof(DbContext), typeof(NorthwindContext));
services.AddEntityFrameworkSqlServer()
.AddDbContext<NorthwindContext>(options =>
{
options.UseSqlServer(configuration.GetConnectionString("DefaultConnection"));
});
return services;
}
我有大致相同但對於 BLL
public static class ServiceCollectionsExtensions
{
public static IServiceCollection RegisterBllServices(this IServiceCollection services, IConfiguration configuration)
{
services.RegisterRepositories(configuration);
services.AddScoped<IProductService, ProductService>();
return services;
}
}
在Startup.cs
表示層中,我有這樣的東西
services.RegisterBllServices(_configuration);
所以現在表示層對DbContext
和我正在使用的ORM
DbContext
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.