簡體   English   中英

是否可以在分層 ASP.NET Core 應用程序中的 DAL 中使用 DbContext?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM