Gop*_*rma 1 c# design-patterns 3-tier asp.net-core asp.net-core-webapi
我正在研究 Web API Core 2.2,需要设计 3 层架构。我该怎么做。
我的项目结构如下
在 Web API 项目中..
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<HrmsDbContext>(opt =>
opt.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
Run Code Online (Sandbox Code Playgroud)
在 DAL(图书馆项目,我制作了我的 DBContext 并提供了如下所示的连接字符串。
有没有更好的方法让我没有在两个地方提供连接字符串?并以良好的方式编写 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;
}
Run Code Online (Sandbox Code Playgroud)
上下文类
public class PaymentDbContext : DbContext
{
public PaymentDbContext(DbContextOptions<PaymentDbContext> options)
: base(options)
{
}
public DbSet<Payments> Payments { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
使用 DI 访问 Context
private readonly PaymentDbContext _context;
public PaymentsRepository(PaymentDbContext dbContext)
{
_context = dbContext;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3897 次 |
| 最近记录: |