简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM