简体   繁体   中英

Is it possible to have DbContext in DAL in layered ASP.NET Core application?

For example, if I have 3 layers:

Data access layer -> Business Logic Layer -> Presentation Layer

is it possible to have a DbContext in the DAL considering I can't reference it from the presentation layer?

If yes, so how can I initialize using DB in Startup.cs if I won't able to see DbContext ?

services.AddEntityFrameworkSqlServer()
        .AddDbContext<DbContext>(options =>
                {
                    ...
                });

I've found such kind of solution of my problem(Considering guys helped me in comments) I have a static class with extension method for 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;
    }

I have approximately the same but for BLL

public static class ServiceCollectionsExtensions
{
    public static IServiceCollection RegisterBllServices(this IServiceCollection services, IConfiguration configuration)
    {
        services.RegisterRepositories(configuration);
        services.AddScoped<IProductService, ProductService>();

        return services;
    }
}

And in Presentation Layer in Startup.cs I have something like this

services.RegisterBllServices(_configuration);

So now Presentation Layers doesn't know anything about DbContext and what ORM I'm using

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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