Git Product home page Git Product logo

cleanarchitecture's Introduction

Clean Architecture Template

.NET Core Matech.Clean.Architecture.Template NuGet Package NuGet

This is a solution template for creating a ASP.NET Core Web API following the principles of Clean Architecture. Create a new project based on this template by clicking the above Use this template button or by installing and running the associated NuGet package (see Getting Started for full details).

Technologies

Getting Started

Install the NuGet package and run dotnet new cas:

  1. Install the latest .NET SDK
  2. Run dotnet new --install Matech.Clean.Architecture.Template to install the project template
  3. Create a folder for your solution and cd into it (the template will use it as project name)
  4. Run dotnet new cas to create a new project
  5. Navigate to src/Apps/CleanArchitecture.Api and run dotnet run to launch the back end (ASP.NET Core Web API)
  6. Open web browser https://localhost:5021/api Swagger UI

Database Configuration

The template is configured to use an in-memory database by default. This ensures that all users will be able to run the solution without needing to set up additional infrastructure (e.g. SQL Server).

If you would like to use SQL Server, you will need to update WebApi/appsettings.json as follows:

  "DbProvider": SqlServer

DbProvider could be Sqlite, SqlServer, Npgsql by default, which could be extended to more database providers that EF Core supports.

Verify that the DefaultConnection connection string within appsettings.json points to a valid SQL Server instance.

Verify that the DefaultConnection_Postgres connection string within appsettings.json points to a valid PostgresSQL instance.

Verify that the DefaultConnection_Sqlite connection string within appsettings.json points to a valid Sqlite connection or in-memory instance.

When you run the application the database will be automatically created (if necessary) and the latest migrations will be applied.

Database Migrations

By moving to multiple databases migrations, every db provider will have one migrations project as below.

  • Sqlite: CleanArchitecture.Infrastructure.Sqlite
  • SqlServer: CleanArchitecture.Infrastructure.SqlServer
  • Npgsql: CleanArchitecture.Infrastructure.Npgsql

Multiple databases migrations

To use dotnet-ef for your migrations please add the following flags to your command (values assume you are executing from repository root)

  • --project src/Common/CleanArchitecture.Infrastructure.{DbProvider}
  • --startup-project src/Apps/CleanArchitecture.Api

For example, to add a new migration from the root folder:

set "DbProvider" in appsettings.json of Api project to Sqlite: dotnet ef migrations add "CreateDb" --project src\Common\CleanArchitecture.Infrastructure.Sqlite --startup-project src\Apps\CleanArchitecture.Api

dotnet ef database update --project src\Common\CleanArchitecture.Infrastructure.Sqlite --startup-project src\Apps\WebApi

set "DbProvider" in appsettings.json of Api project to SqlServer: dotnet ef migrations add "CreateDb" --project src\Common\CleanArchitecture.Infrastructure.SqlServe --startup-project src\Apps\CleanArchitecture.Api

dotnet ef database update --project src\Common\CleanArchitecture.Infrastructure.SqlServer --startup-project src\Apps\WebApi

set "DbProvider" in appsettings.json of Api project to Npgsql: dotnet ef migrations add "CreateDb" --project src\Common\CleanArchitecture.Infrastructure.Npgsql --startup-project src\Apps\CleanArchitecture.Api

dotnet ef database update --project src\Common\CleanArchitecture.Infrastructure.Npgsql --startup-project src\Apps\WebApi

Overview

Domain

This will contain all entities, enums, exceptions, interfaces, types and logic specific to the domain layer.

Application

This layer contains all application logic. It is dependent on the domain layer, but has no dependencies on any other layer or project. This layer defines interfaces that are implemented by outside layers. For example, if the application need to access a notification service, a new interface would be added to application and an implementation would be created within infrastructure.

Infrastructure

This layer contains classes for accessing external resources such as file systems, web services, smtp, and so on. These classes should be based on interfaces defined within the application layer.

WebApi

This layer is a web api application based on ASP.NET 6.0.x. This layer depends on both the Application and Infrastructure layers, however, the dependency on Infrastructure is only to support dependency injection. Therefore only Startup.cs should reference Infrastructure.

Logs

Logging into Elasticsearch using Serilog and viewing logs in Kibana.

Prerequisites

Open CLI in the project folder and run the below comment.

PS CleanArchitecture> docker-compose up

docker-compose.yml pull and run the ElasticSearch and Kibana images.

If you are running first time Windows 10 WSL 2 (Windows Subsystem for Linux) Linux Container for Docker, You will probably get the following error from the docker.

Error: max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144]

Solution: Open the Linux WSL 2 terminal sudo sysctl -w vm.max_map_count=262144 and change the virtual memory for Linux.

Support

If you are having problems, please let us know by raising a new issue.

License

This project is licensed with the MIT license.

cleanarchitecture's People

Contributors

bulentsiyah-softtech avatar david-x-chen avatar iayti avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cleanarchitecture's Issues

Docker Container is not running on Windows 10

Describe the bug
failed to solve: rpc error: code = Unknown desc = executor failed running [/bin/sh -c dotnet restore
"src/Apps/ProjName.Api/ProjName.Api.csproj"]: exit code: 1

To Reproduce
Steps to reproduce the behavior:

  1. Create the new template using dotnet new --install Matech.Clean.Architecture.Template
  2. Downloading the Docker desktop
  3. Going to the folder and running command docker-compose up

Expected behavior
The Docker images got up and running

Desktop (please complete the following information):

  • OS: [Windows 10]
  • Browser: NA
  • Version: 1.1.1.2

Microservice Architecture Service Meshes, API Gateways, and Message Queues

API Gateways

  • Ocelot
  • Tyk
  • Kong
  • AWS API Gateway, Azure Api Management or Google Cloud Endpoints

Service Meshes

Message Queues

Technologies

I am really interested in using Dapr. We can use service mesh like Linkerd and message queues like RabbitMQ with Dapr.

We can use service meshes to manage the network between microservices. If we need message queues, it can be used with Dapr bindings RabbitMQ.

I'm waiting for suggestions. Thank you for your attention.

How to have Navigation in User Model and Other Entities

Since Our Identity models are in the Infrastructure Layer and other Entities are in the Domain Layer, I was wonder to know how can we have navigation between an Entity and User Model?

For instance, I have two models, User and Content, Each user has 0 or many contents so there should be a List in User Model, and in Content there should be a foreign Key of User

Public class User{

 Public List<Content> Contents{get;set;}

}

Problem with identity server 4

Hello, I'm trying to setup identity server 4 for production, and the application keeps erroring out when it runs in production mode, any idea how I can solve this?

DenyAnonymousAuthorizationRequirement: Requires an authenticated user

This probably isn't a bug, just me not understanding .NET 5 + AspNetCore libraries, so I didn't click Bug Report just yet.

I followed the steps on the README but when trying it out through Swagger (the URL that pops up) it doesn't seem to authenticate. I tried using Super_Secret_Key as the token to authorize but got this...

image

and in console, the message that's in the subject of this issue.

Sorry, I'm still learning the AspNetCore libraries. Thanks for being patient with me. I have a lot of webapp experience and .NET Framework but haven't made my way into the .NET 5 API world until now.

I did get it working if I use Client.WorkerService... is it just the Swagger script that isn't working?

I tried through Postman with the same response. How would one authenticate through an API key?

Can you guide me to the right spot to add authorized tokens, or if it's just one token like Super_Secret_Key let me know what I'm doing wrong.

Thank you very much!

Authorize with Policy show 'The type or namespace could not be found'

Hi, I facing the issues with Authorize attribute when using policy

Since in your code using custom authorize class, so I unable to implement policy here.

If using Microsoft.AspNetCore.Authorization.AuthorizeAttribute, then the authorization is not working.

Example

//Need use this, or else show an error 'The type or namespace could not be found'
using AuthorizeAttribute = Microsoft.AspNetCore.Authorization.AuthorizeAttribute;


[HttpPost]
[Route("uom")]
[Authorize(Policy = "user.read.policy")] // Is not working
[ProducesResponseType(typeof(ServiceResult<ItemUomDto>), (int)HttpStatusCode.OK)]
public async Task<ActionResult<ServiceResult<ItemUomDto>>> Create([FromBody] CreateItemUomCommand command)
{
     return Ok(await Mediator.Send(command));
}

Any idea how we can solve?

Duplication in mediator handlers

How to use duplicate code in handler?
Does the static method take up a lot of memory when a lot of data is exchanged?
Base on @ShreyasJejurkar
It's not recommended to send another request from request handlers. The purpose of using MeditR is just to convert HTTP requests to our application-specific requests and send them into the application layer without letting the controller knows about it or any other presentation layer.

What is the best solution to not occupy a lot of memory?
Static method or utility class or service or Application services or abstraction layers or domain layer?

What is the code you suggest?

Return Task<ServiceResult> without <T>

Based on this code

 public async Task<ServiceResult<CityDto>> Handle(UpdateCityCommand request, CancellationToken cancellationToken)
        {
            var entity = await _context.Cities.FindAsync(request.Id);

            if (entity == null)
            {
                throw new NotFoundException(nameof(City), request.Id);
            }
            if (!string.IsNullOrEmpty(request.Name))
                entity.Name = request.Name;
            entity.Active = request.Active;

            await _context.SaveChangesAsync(cancellationToken);

            return ServiceResult.Success(_mapper.Map<CityDto>(entity));
        }

Any I idea how I can return ServiceResult without Dto? I just want to return public async Task<ServiceResult> Handle(UpdateCityCommand request, CancellationToken cancellationToken)

In some case, I just want to tell success only

Thanks in advance.

Adding Polly's Circuit Breaker

Polly is a .NET resilience and transient-fault-handling library that allows developers to express policies such as Retry, Circuit Breaker, Timeout, Bulkhead Isolation, and Fallback in a fluent and thread-safe manner

Occasionally receive 401 (Unauthorized)

I occasionally receive the error 401 (Unauthorized) after login. I am then required to restart the application pool and it will work fine again for a few days or sometimes weeks.

Not a big application or complicated app by any means (< 10 users and not much more complicated than the todo sample code). Memory usage is below 200 MB.

I am fairly new to Web API, Angular, and IdentiyServer programming so I assume the problem is something I am doing wrong.

Any ideas on where to look are highly appreciated.

Clean architecture with EF Core DB First approach

Hi,

I am implementing clean architecture using the existing database, with scaffolding command I have generated the POCO entities in the Infrastructure layer and as well as manually created the entities in the domain layer to map them later.

in the Application layer, I have the generic interface repository with a few standard operations.

public interface IRepository<T> where T : class
 {
     Task<IReadOnlyList<T>> GetAllAsync();
     Task<T> GetByIdAsync(int id);
     Task<T> AddAsync(T entity);
     Task UpdateAsync(T entity);
     Task DeleteAsync(T entity);
 }

As per the principles of Clean-Architecture, I am implementing it in the Infrastructure layer.

public class Repository<T> : IRepository<T> where T : class
    {

        protected readonly MyDBContext _MyDBContext;
        public Repository( MyDBContext mydbContext)
        {
            _MyDBContext= mydbContext;
        }
        public async Task<T> AddAsync(T entity)
        {
            await _MyDBContext.Set<T>().AddAsync(entity);
            await _MyDBContext.SaveChangesAsync();
            return entity;
        }

-----
----

As per the template, I am using a Mediator pattern with CQRS, when I try to save the user from the API layer I will end up with the below exception.

System.InvalidOperationException: Cannot create a DbSet for 'ABC.Domain.Entities.User' because this type is not included in the model for the context. However, the model contains an entity type with the same name in a different namespace: 'ABC.Infrastructure.Models.User'.

It will be resolved if I can able to map the domain entity to the infrastructure entity in the above Repository implementation.
In the above implementation, the T is the ABC.Domain.Entities.User, not the ABC.Infrastructure.Models.User. I can't pass the ABC.Infrastructure.Models.User from the Application layer ( because I can't add a reference to the Infrastructure layer in Application layer) due to the rule Clean Architecture all dependencies flow inwards and Core has no dependency on any other layer.

Please help me to map the incoming domain entity with the infrastructure entity in the above repository implementation so that I can use these general methods for other entity operations as well.

@iayti .. Please do the needful.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.