C# ASP NET WEB API. Api. Application. Domain. Infrastructure. Объясни для чего нужны и…
- User
C# ASP NET WEB API. Api. Application. Domain. Infrastructure. Объясни для чего нужны и приведи пример с кодом
- Assistant
C# ASP NET WEB API. Api. Application. Domain. Infrastructure. Объясни для чего нужны и приведи пример с кодом
In a well-structured C# ASP.NET Web API application, organizing your code into distinct layers such as API, Application, Domain, and Infrastructure promotes maintainability, scalability, and separation of concerns. This approach is often inspired by Clean Architecture principles.
API (Presentation Layer)
Application Layer
Domain Layer
Infrastructure Layer
Let's build a simple ToDo application demonstrating these layers. We'll assume the use of Entity Framework Core for data access.
Project: MyApp.Domain
Defines the core business entities and logic.
// MyApp.Domain/Entities/ToDoItem.cs
namespace MyApp.Domain.Entities
{
public class ToDoItem
{
public Guid Id { get; set; } = Guid.NewGuid();
public string Title { get; set; }
public bool IsCompleted { get; set; }
// Business logic can be added here
public void MarkAsCompleted()
{
IsCompleted = true;
}
}
}
Project: MyApp.Application
Contains interfaces and application services.
// MyApp.Application/Interfaces/IToDoRepository.cs
using MyApp.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace MyApp.Application.Interfaces
{
public interface IToDoRepository
{
Task<IEnumerable<ToDoItem>> GetAllAsync();
Task<ToDoItem> GetByIdAsync(Guid id);
Task AddAsync(ToDoItem item);
Task UpdateAsync(ToDoItem item);
Task DeleteAsync(Guid id);
}
}
// MyApp.Application/Services/ToDoService.cs
using MyApp.Application.Interfaces;
using MyApp.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace MyApp.Application.Services
{
public class ToDoService
{
private readonly IToDoRepository _repository;
public ToDoService(IToDoRepository repository)
{
_repository = repository;
}
public async Task<IEnumerable<ToDoItem>> GetToDosAsync()
{
return await _repository.GetAllAsync();
}
public async Task<ToDoItem> GetToDoByIdAsync(Guid id)
{
return await _repository.GetByIdAsync(id);
}
public async Task AddToDoAsync(ToDoItem item)
{
// Additional application logic can be added here
await _repository.AddAsync(item);
}
public async Task UpdateToDoAsync(ToDoItem item)
{
// Additional application logic can be added here
await _repository.UpdateAsync(item);
}
public async Task DeleteToDoAsync(Guid id)
{
await _repository.DeleteAsync(id);
}
}
}
Project: MyApp.Infrastructure
Implements data access using Entity Framework Core.
// MyApp.Infrastructure/Data/ToDoDbContext.cs
using Microsoft.EntityFrameworkCore;
using MyApp.Domain.Entities;
namespace MyApp.Infrastructure.Data
{
public class ToDoDbContext : DbContext
{
public ToDoDbContext(DbContextOptions<ToDoDbContext> options)
: base(options)
{
}
public DbSet<ToDoItem> ToDoItems { get; set; }
}
}
// MyApp.Infrastructure/Repositories/ToDoRepository.cs
using MyApp.Application.Interfaces;
using MyApp.Domain.Entities;
using MyApp.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace MyApp.Infrastructure.Repositories
{
public class ToDoRepository : IToDoRepository
{
private readonly ToDoDbContext _context;
public ToDoRepository(ToDoDbContext context)
{
_context = context;
}
public async Task<IEnumerable<ToDoItem>> GetAllAsync()
{
return await _context.ToDoItems.ToListAsync();
}
public async Task<ToDoItem> GetByIdAsync(Guid id)
{
return await _context.ToDoItems.FindAsync(id);
}
public async Task AddAsync(ToDoItem item)
{
_context.ToDoItems.Add(item);
await _context.SaveChangesAsync();
}
public async Task UpdateAsync(ToDoItem item)
{
_context.ToDoItems.Update(item);
await _context.SaveChangesAsync();
}
public async Task DeleteAsync(Guid id)
{
var item = await _context.ToDoItems.FindAsync(id);
if (item != null)
{
_context.ToDoItems.Remove(item);
await _context.SaveChangesAsync();
}
}
}
}
Project: MyApp.Api
Defines the Web API controllers and configures dependency injection.
// MyApp.Api/Controllers/ToDoController.cs
using Microsoft.AspNetCore.Mvc;
using MyApp.Application.Services;
using MyApp.Domain.Entities;
using System;
using System.Threading.Tasks;
namespace MyApp.Api.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class ToDoController : ControllerBase
{
private readonly ToDoService _service;
public ToDoController(ToDoService service)
{
_service = service;
}
[HttpGet]
public async Task<IActionResult> GetAll()
{
var items = await _service.GetToDosAsync();
return Ok(items);
}
[HttpGet("{id}")]
public async Task<IActionResult> GetById(Guid id)
{
var item = await _service.GetToDoByIdAsync(id);
if (item == null)
return NotFound();
return Ok(item);
}
[HttpPost]
public async Task<IActionResult> Create([FromBody] ToDoItem item)
{
await _service.AddToDoAsync(item);
return CreatedAtAction(nameof(GetById), new { id = item.Id }, item);
}
[HttpPut("{id}")]
public async Task<IActionResult> Update(Guid id, [FromBody] ToDoItem item)
{
if (id != item.Id)
return BadRequest();
var existingItem = await _service.GetToDoByIdAsync(id);
if (existingItem == null)
return NotFound();
await _service.UpdateToDoAsync(item);
return NoContent();
}
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(Guid id)
{
var existingItem = await _service.GetToDoByIdAsync(id);
if (existingItem == null)
return NotFound();
await _service.DeleteToDoAsync(id);
return NoContent();
}
}
}
// MyApp.Api/Program.cs
using Microsoft.EntityFrameworkCore;
using MyApp.Application.Interfaces;
using MyApp.Application.Services;
using MyApp.Infrastructure.Data;
using MyApp.Infrastructure.Repositories;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Database configuration
builder.Services.AddDbContext<ToDoDbContext>(options =>
options.UseInMemoryDatabase("ToDoDb")); // Using InMemory for simplicity
// Dependency Injection
builder.Services.AddScoped<IToDoRepository, ToDoRepository>();
builder.Services.AddScoped<ToDoService>();
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseSwagger();
app.UseSwaggerUI();
app.UseAuthorization();
app.MapControllers();
app.Run();
Domain Layer (MyApp.Domain):
ToDoItem entity, representing a to-do task with properties like Id, Title, and IsCompleted.MarkAsCompleted method, which encapsulates behavior related to completing a to-do item.Application Layer (MyApp.Application):
IToDoRepository interface, abstracting data access operations for ToDoItem.ToDoService, which contains methods to handle use cases like retrieving all to-dos, adding a new to-do, updating, and deleting. It uses the repository interface to interact with the data.Infrastructure Layer (MyApp.Infrastructure):
ToDoDbContext using Entity Framework Core with an in-memory database for simplicity.IToDoRepository in ToDoRepository, handling actual data operations against the ToDoDbContext.API Layer (MyApp.Api):
ToDoController, which defines API endpoints for CRUD operations on to-do items.Program.cs to wire up the services, repositories, and database context.Prerequisites:
Steps:
MyApp.Domain, MyApp.Application, MyApp.Infrastructure, and MyApp.Api.MyApp.Application references MyApp.Domain.MyApp.Infrastructure references MyApp.Domain and MyApp.Application.MyApp.Api references MyApp.Application and MyApp.Infrastructure.MyApp.Api project.https://localhost:{port}/swagger) to interact with the API endpoints.Organizing your ASP.NET Web API application into API, Application, Domain, and Infrastructure layers fosters a clean architecture that is easy to maintain, test, and scale. Each layer has a clear responsibility, reducing dependencies and enhancing the overall structure of the application.