Skip to main content
 首页 » 编程设计

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

2024年02月25日35kevingrace

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

我的项目结构如下

在 Web API 项目中..

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

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

有没有更好的方法让我在两个地方都没有提供connectionstring?并以良好的方式编写 3 层架构。

任何帮助将不胜感激。

请您参考如下方法:

层与层

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

层 - 层只是应用组件的物理分隔。

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

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

现在,如果您的数据访问托管在不同的机器/服务器上,并且您的业务也托管在不同的机器/服务器上,那么您现在将拥有 3 层的 3 层应用。

设置连接字符串

您在启动时引用了连接字符串并添加到服务中。您不需要再次定义连接字符串并使用内置 DI 的数据库上下文。 代码可能如下所示!

开始上课

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 访问 Context

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