Need help with Architecture?
Click the “chat” button below for chat support from the developer who created it, or find similar developers for support.

About the developer

rafaelfgx
2.0K Stars 545 Forks MIT License 1 Commits 0 Opened issues

Description

.NET 5, ASP.NET Core 5, Entity Framework Core 5, C# 9, Angular 11, Clean Code, SOLID, DDD.

Services available

!
?

Need anything else?

Contributors list

# 7,946
Angular
.NET
dotnet5
C#
1 commit

Architecture

This project is an example of architecture using new technologies and best practices.

The goal is to share knowledge and use it as reference for new projects.

Thanks for enjoying!

Technologies

Practices

  • Clean Architecture
  • Clean Code
  • SOLID Principles
  • Separation of Concerns
  • DDD (Domain-Driven Design)

Run

Command Line

Prerequisites

Steps

  1. Open directory source\Web\Frontend in command line and execute npm run restore.
  2. Open directory source\Web in command line and execute dotnet run.
  3. Open https:.

Visual Studio Code

Prerequisites

Steps

  1. Open directory source\Web\Frontend in command line and execute npm run restore.
  2. Open source directory in Visual Studio Code.
  3. Press F5.
Visual Studio

Prerequisites

Steps

  1. Open directory source\Web\Frontend in command line and execute npm run restore.
  2. Open source\Architecture.sln in Visual Studio.
  3. Set Architecture.Web as startup project.
  4. Press F5.
Docker

Prerequisites

Steps

  1. Execute docker-compose up --build -d in root directory.
  2. Open http:.

Nuget Packages

Source: https://github.com/rafaelfgx/DotNetCore

Published: https://www.nuget.org/profiles/rafaelfgx

Layers

Web: Frontend and API.

Application: Flow control.

Domain: Business rules and domain logic.

Model: Data transfer objects.

Database: Data persistence.

Web

Frontend

Service

export class AppCustomerService {
    constructor(private readonly http: HttpClient, private readonly gridService: GridService) { }

add = (customer: Customer) =&gt; this.http.post<number>("customers", customer);

delete = (id: number) =&gt; this.http.delete(`customers/${id}`);

get = (id: number) =&gt; this.http.get<customer>(`customers/${id}`);

grid = (parameters: GridParameters) =&gt; this.gridService.get<customer>("customers/grid", parameters);

inactivate = (id: number) =&gt; this.http.patch(`customers/${id}/inactivate`, {});

list = () =&gt; this.http.get<customer>("customers");

update = (customer: Customer) =&gt; this.http.put(`customers/${customer.id}`, customer);

}

Guard

export class AppGuard implements CanActivate {
    constructor(private readonly appAuthService: AppAuthService) { }

canActivate() {
    if (this.appAuthService.authenticated()) { return true; }
    this.appAuthService.signin();
    return false;
}

}

ErrorHandler

export class AppErrorHandler implements ErrorHandler {
    constructor(private readonly appModalService: AppModalService) { }

handleError(error: any) {
    if (error instanceof HttpErrorResponse) {
        switch (error.status) {
            case 422: { this.appModalService.alert(error.error); return; }
        }
    }

    console.error(error);
}

}

HttpInterceptor

export class AppHttpInterceptor implements HttpInterceptor {
    constructor(private readonly appAuthService: AppAuthService) { }

intercept(request: HttpRequest<any>, next: HttpHandler) {
    request = request.clone({
        setHeaders: { Authorization: `Bearer ${this.appAuthService.token()}` }
    });

    return next.handle(request);
}

}

API

Startup

public sealed class Startup
{
    public void Configure(IApplicationBuilder application)
    {
        application.UseException();
        application.UseHttps();
        application.UseRouting();
        application.UseResponseCompression();
        application.UseAuthentication();
        application.UseAuthorization();
        application.UseEndpoints();
        application.UseSpa();
    }

public void ConfigureServices(IServiceCollection services)
{
    services.AddSecurity();
    services.AddResponseCompression();
    services.AddControllersMvcJsonOptions();
    services.AddSpa();
    services.AddContext();
    services.AddServices();
}

}

Controller

[ApiController]
[Route("customers")]
public sealed class CustomerController : ControllerBase
{
    private readonly ICustomerService _customerService;

public CustomerController(ICustomerService customerService) =&gt; _customerService = customerService;

[HttpPost]
public IActionResult Add(CustomerModel model) =&gt; _customerService.AddAsync(model).ApiResult();

[HttpDelete("{id}")]
public IActionResult Delete(long id) =&gt; _customerService.DeleteAsync(id).ApiResult();

[HttpGet("{id}")]
public IActionResult Get(long id) =&gt; _customerService.GetAsync(id).ApiResult();

[HttpGet("grid")]
public IActionResult Grid([FromQuery] GridParameters parameters) =&gt; _customerService.GridAsync(parameters).ApiResult();

[HttpPatch("{id}/inactivate")]
public Task InactivateAsync(long id) =&gt; _customerService.InactivateAsync(id);

[HttpGet]
public IActionResult List() =&gt; _customerService.ListAsync().ApiResult();

[HttpPut("{id}")]
public IActionResult Update(CustomerModel model) =&gt; _customerService.UpdateAsync(model).ApiResult();

}

Application

Service

public sealed class CustomerService : ICustomerService
{
    private readonly ICustomerFactory _customerFactory;
    private readonly ICustomerRepository _customerRepository;
    private readonly IUnitOfWork _unitOfWork;

public CustomerService
(
    ICustomerFactory customerFactory,
    ICustomerRepository customerRepository,
    IUnitOfWork unitOfWork
)
{
    _customerFactory = customerFactory;
    _customerRepository = customerRepository;
    _unitOfWork = unitOfWork;
}

public async Task<iresult>&gt; AddAsync(CustomerModel model)
{
    var validation = new AddCustomerModelValidator().Validation(model);

    if (validation.Failed) return validation.Fail<long>();

    var customer = _customerFactory.Create(model);

    await _customerRepository.AddAsync(customer);

    await _unitOfWork.SaveChangesAsync();

    return customer.Id.Success();
}

public async Task<iresult> DeleteAsync(long id)
{
    await _customerRepository.DeleteAsync(id);

    await _unitOfWork.SaveChangesAsync();

    return Result.Success();
}

public Task<customermodel> GetAsync(long id)
{
    return _customerRepository.GetModelAsync(id);
}

public Task<grid>&gt; GridAsync(GridParameters parameters)
{
    return _customerRepository.GridAsync(parameters);
}

public async Task InactivateAsync(long id)
{
    var customer = new Customer(id);

    customer.Inactivate();

    await _customerRepository.InactivateAsync(customer);

    await _unitOfWork.SaveChangesAsync();
}

public Task<ienumerable>&gt; ListAsync()
{
    return _customerRepository.ListModelAsync();
}

public async Task<iresult> UpdateAsync(CustomerModel model)
{
    var validation = new UpdateCustomerModelValidator().Validation(model);

    if (validation.Failed) return validation;

    var customer = _customerFactory.Create(model);

    await _customerRepository.UpdateAsync(customer.Id, customer);

    await _unitOfWork.SaveChangesAsync();

    return Result.Success();
}

}

Factory

public sealed class CustomerFactory : ICustomerFactory
{
    public Customer Create(CustomerModel model)
    {
        return new Customer
        (
            model.Id,
            new Name(model.FirstName, model.LastName),
            new Email(model.Email)
        );
    }
}

Domain

Entity

public sealed class Customer : Entity
{
    public Customer(long id) : base(id) { }

public Customer
(
    long id,
    Name name,
    Email email
)
: base(id)
{
    Name = name;
    Email = email;
    Activate();
}

public Name Name { get; private set; }

public Email Email { get; private set; }

public Status Status { get; private set; }

public void Activate()
{
    Status = Status.Active;
}

public void Inactivate()
{
    Status = Status.Inactive;
}

}

ValueObject

public sealed record Name(string FirstName, string LastName);

Model

Model

public sealed record CustomerModel
{
    public long Id { get; init; }

public string FirstName { get; init; }

public string LastName { get; init; }

public string Email { get; init; }

}

ModelValidator

public abstract class CustomerModelValidator : AbstractValidator
{
    public void Id() => RuleFor(customer => customer.Id).NotEmpty();

public void FirstName() =&gt; RuleFor(customer =&gt; customer.FirstName).NotEmpty();

public void LastName() =&gt; RuleFor(customer =&gt; customer.LastName).NotEmpty();

public void Email() =&gt; RuleFor(customer =&gt; customer.Email).EmailAddress();

}

public sealed class AddCustomerModelValidator : CustomerModelValidator
{
    public AddCustomerModelValidator() => FirstName(); LastName(); Email();
}
public sealed class UpdateCustomerModelValidator : CustomerModelValidator
{
    public UpdateCustomerModelValidator() => Id(); FirstName(); LastName(); Email();
}

Database

Context

public sealed class Context : DbContext
{
    public Context(DbContextOptions options) : base(options) { }

protected override void OnModelCreating(ModelBuilder builder)
{
    builder.ApplyConfigurationsFromAssembly(typeof(Context).Assembly).Seed();
}

}

Configuration

public sealed class CustomerConfiguration : IEntityTypeConfiguration
{
    public void Configure(EntityTypeBuilder builder)
    {
        builder.ToTable(nameof(Customer), nameof(Customer));

    builder.HasKey(customer =&gt; customer.Id);

    builder.Property(customer =&gt; customer.Id).ValueGeneratedOnAdd().IsRequired();

    builder.Property(customer =&gt; customer.Status).IsRequired();

    builder.OwnsOne(customer =&gt; customer.Name, customerName =&gt;
    {
        customerName.Property(name =&gt; name.FirstName).HasColumnName(nameof(Name.FirstName)).HasMaxLength(100).IsRequired();

        customerName.Property(name =&gt; name.LastName).HasColumnName(nameof(Name.LastName)).HasMaxLength(200).IsRequired();
    });

    builder.OwnsOne(customer =&gt; customer.Email, customerEmail =&gt;
    {
        customerEmail.Property(email =&gt; email.Value).HasColumnName(nameof(User.Email)).HasMaxLength(300).IsRequired();

        customerEmail.HasIndex(email =&gt; email.Value).IsUnique();
    });
}

}

Repository

public sealed class CustomerRepository : EFRepository, ICustomerRepository
{
    public CustomerRepository(Context context) : base(context) { }

public Task<customermodel> GetModelAsync(long id)
{
    return Queryable.Where(CustomerExpression.Id(id)).Select(CustomerExpression.Model).SingleOrDefaultAsync();
}

public Task<grid>&gt; GridAsync(GridParameters parameters)
{
    return Queryable.Select(CustomerExpression.Model).GridAsync(parameters);
}

public Task InactivateAsync(Customer customer)
{
    return UpdatePartialAsync(customer.Id, new { customer.Status });
}

public async Task<ienumerable>&gt; ListModelAsync()
{
    return await Queryable.Select(CustomerExpression.Model).ToListAsync();
}

}

Expression

public static class CustomerExpression
{
    public static Expression> Model => customer => new CustomerModel
    {
        Id = user.Id,
        FirstName = user.Name.FirstName,
        LastName = user.Name.LastName,
        Email = user.Email.Value
    };

public static Expression<func bool>&gt; Id(long id) =&gt; customer =&gt; customer.Id == id;

}

We use cookies. If you continue to browse the site, you agree to the use of cookies. For more information on our use of cookies please see our Privacy Policy.