Create 3 Tier Architecture In DotNet Core 2.2 Web API C#

风格不统一 提交于 2020-02-25 06:59:14

问题


I am working on Web API Core 2.2 and need to design 3 tier architecture. How can I do it.

My Project Structure as below

In Web API Project..

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

In DAL (Library project, I have made my DBContext and provided connectionstring like below.

Is there any better so that I had not provide connectionstring at two places? and write 3 tier architecture in good way.

Any help will be appreciated.


回答1:


Layer vs Tier

You question is around layers and not tiers.

Tiers- A Tier is simply the physical separation of your app components.

Layers- Layers act as more logical separators that exist to separate and organize your actual code. You'll often hear terms like "Business Logic Layer", "Presentation Layer" and others. These are simply ways to organize all of the code within your application.

If you have a web app that contains your Data Access and Business Logic which is running on the same machine/Server, then you will have 3-layered app in 1-Tier.

Now if your Data Access is hosted on different machine/server, and your Business is also hosted in different machine/server, then you will now have a 3-layered app in 3-Tier.

Set Connection String

You have referenced connection string in your start up and added to services. You don't need to define the connection string again and use the db context using Built in DI. The code could look like this !

Start up class

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;
}

Context Class

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

        }

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


    }    

Use DI to access Context

 private readonly PaymentDbContext _context;


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


来源:https://stackoverflow.com/questions/55566872/create-3-tier-architecture-in-dotnet-core-2-2-web-api-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!