【问题标题】:Is it possible to have DbContext in DAL in layered ASP.NET Core application?在分层的 ASP.NET Core 应用程序中是否可以在 DAL 中使用 DbContext?
【发布时间】:2018-09-26 19:40:20
【问题描述】:

例如,如果我有 3 层:

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

考虑到我无法从表示层引用它,是否可以在 DAL 中使用 DbContext

如果是,那么如果我看不到DbContext,我该如何使用Startup.cs 中的DB 进行初始化?

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

【问题讨论】:

  • 如果表示层是组合根为什么不能引用上下文?
  • 您总是可以公开某种形式的配置,这些配置会通过另一层冒泡,以便在组合根处调用。它不一定必须公开 DbContext,但它需要能够访问服务集合才能添加配置它。
  • 如果你添加DAL项目引用到Presentation layer,你可以引用DbContext,分享一下你不能从Presentation layer引用的原因。
  • @Nkosi 你能提供一个冒泡配置的小例子吗?无法理解它的外观。
  • DbContext 基本上是您的 DAL。如果您的应用引用了引用 DAL 的 BLL,那么您的应用将间接引用 DAL,DbContext 将在 Startup.cs 中非常有用。

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


【解决方案1】:

我找到了解决问题的方法(考虑到有人在 cmets 中帮助了我) 我有一个带有 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 一无所知

【讨论】:

    猜你喜欢
    • 2019-10-23
    • 2018-10-25
    • 2018-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多