分层ASP.NET Core应用程序中的DAL中是否可能有DbContext?

时间:2018-09-25 22:54:16

标签: c# asp.net-core architecture ef-core-2.1

例如,如果我有3层:

DbContext

考虑到我不能从表示层引用它,是否有可能在DAL中有一个Startup.cs

如果是,那么如果看不到DbContext,如何在services.AddEntityFrameworkSqlServer() .AddDbContext<DbContext>(options => { ... }); 中使用DB进行初始化?

AccountValues = [
{'portfolio_ref': 1, 'tag': 'FullInit', 'value': '20642.95', 'currency': 'USD', 'percent': 0.0}, 
{'portfolio_ref': 1, 'tag': 'FullMaint', 'value': '21350.54', 'currency': 'USD', 'percent': 0.0}, 
{'portfolio_ref': 1, 'tag': 'NetLiq', 'value': '70976.05', 'currency': 'USD', 'percent': 100.0} ]

1 个答案:

答案 0 :(得分:1)

我已经找到了解决问题的方法(考虑的人在评论中帮助了我) 我有一个静态类,其扩展方法为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);

因此,现在Presentation Layers对DbContext以及我正在使用的ORM一无所知

相关问题