我正在研究Web API Core 2.2,需要设计3层体系结构。
我该怎么做。

我的项目结构如下

c# - 在DotNet Core 2.2 Web API C#中创建3层架构-LMLPHP

在Web API项目中。

public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<HrmsDbContext>(opt =>
              opt.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}


在DAL(图书馆项目中,我制作了DBContext并提供了如下所示的连接字符串。

c# - 在DotNet Core 2.2 Web API C#中创建3层架构-LMLPHP

有没有更好的方法,所以我没有在两个地方提供连接字符串?并以良好的方式编写3层架构。

任何帮助将不胜感激。

最佳答案

层与层

您的问题是围绕层而不是层。

层-层只是应用程序组件的物理隔离。

层-层充当更多逻辑分隔符,用于分隔和组织您的实际代码。您会经常听到诸如“业务逻辑层”,“演示层”之类的术语。这些只是组织应用程序中所有代码的简单方法。

如果您的Web应用程序包含在同一台计算机/服务器上运行的数据访问和业务逻辑,则您将在1层中拥有3层应用程序。

现在,如果您的数据访问托管在不同的计算机/服务器上,而您的业务也托管在其他的计算机/服务器上,那么您现在将在3层中拥有3层应用程序。

设置连接字符串

您已经在启动时引用了连接字符串,并将其添加到服务中。您无需再次定义连接字符串,也无需通过内置DI使用db上下文。
代码看起来像这样!

上课

public static IServiceCollection AddCustomDbContext(this IServiceCollection services, IConfiguration configuration)
{

    // Add DbContext using SQL Server Provider
    services.AddDbContext<PaymentDbContext>(options =>
        options.UseSqlServer(configuration.GetConnectionString("myconnectionstring"), x => x.MigrationsAssembly("Payment.Persistence")));

    return services;
}


上下文类

public class PaymentDbContext : DbContext
    {
        public PaymentDbContext(DbContextOptions<PaymentDbContext> options)
            : base(options)
        {

        }

        public DbSet<Payments> Payments { get; set; }


    }


使用DI访问上下文

 private readonly PaymentDbContext _context;


 public PaymentsRepository(PaymentDbContext dbContext)
 {
 _context = dbContext;
}

10-02 01:24