在DotNet Core 2.2 Web API C#中创建3层体系结构

问题描述 投票:0回答:1

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

我的项目结构如下

enter image description here

在Web API项目中..

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

在DAL(库项目中,我已经创建了我的DBContext并提供了如下所示的连接字符串。

enter image description here

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

任何帮助将不胜感激。

c# asp.net-core design-patterns asp.net-core-webapi 3-tier
1个回答
3
投票

Layer vs Tier

你的问题是关于层而不是层。

Tiers- A Tier只是应用程序组件的物理分离。

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

如果您的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;
}
© www.soinside.com 2019 - 2024. All rights reserved.