├── ASPNetCore.CleanArchitecture
├── ASPNetCore.CleanArchitecture.Api
│ ├── appsettings.Development.json
│ ├── appsettings.json
│ ├── Controllers
│ │ ├── QueriesParams
│ │ │ ├── BaseQueryParams
│ │ │ │ ├── IBaseQueryParams.cs
│ │ │ │ ├── ISortOrder.cs
│ │ │ │ ├── IPagingQueryParams.cs
│ │ │ │ ├── ISearchQueryParams.cs
│ │ │ │ └── ISortQueryParams.cs
│ │ │ └── IProductQueryParams.cs
│ │ ├── OrdersController.cs
│ │ ├── CustomersController.cs
│ │ └── ProductsController.cs
│ ├── nlog.config
│ ├── ViewModels
│ │ ├── Order
│ │ │ └── OrderViewModel.cs
│ │ ├── Product
│ │ │ └── ProductViewModel.cs
│ │ └── Customer
│ │ │ └── CustomerViewModel.cs
│ ├── Program.cs
│ ├── Filters
│ │ ├── ValidateModelSateAttribute.cs
│ │ └── OpenAPI
│ │ │ ├── RemoveVersionFromParameter.cs
│ │ │ └── ReplaceVersionWithExactValueInPath.cs
│ ├── Mapping
│ │ └── ApiProfile.cs
│ ├── Properties
│ │ └── launchSettings.json
│ ├── Extensions
│ │ ├── ControllerBaseExtensions.cs
│ │ ├── ApplicationBuilderExtensions.cs
│ │ └── ServiceCollectionExtensions.cs
│ ├── ASPNetCore.CleanArchitecture.Api.csproj
│ ├── Middlewares
│ │ └── AppExceptionsMiddleware.cs
│ └── Startup.cs
├── ASPNetCore.CleanArchitecture.Models
│ ├── ASPNetCore.CleanArchitecture.Models.csproj
│ ├── OrderModel.cs
│ ├── Attributes
│ │ └── EntityNameAttribute.cs
│ ├── ProductModel.cs
│ └── CustomerModel.cs
├── ASPNetCore.CleanArchitecture.Interfaces
│ ├── IInjectable .cs
│ ├── IServices
│ │ ├── IOrderService.cs
│ │ ├── ICustomerService.cs
│ │ ├── IProductService.cs
│ │ ├── IGenericService.cs
│ │ └── IBaseService.cs
│ ├── IRepositories
│ │ ├── IOrderRepository.cs
│ │ ├── IProductRepository.cs
│ │ ├── ICustomerRepository.cs
│ │ ├── IBaseRepository.cs
│ │ └── IGenericRepository.cs
│ └── ASPNetCore.CleanArchitecture.Interfaces.csproj
├── ASPNetCore.CleanArchitecture.Exceptions
│ ├── ASPNetCore.CleanArchitecture.Exceptions.csproj
│ ├── AppException.cs
│ ├── ExceptionDetails.cs
│ └── ExceptionsCodes.cs
├── ASPNetCore.CleanArchitecture.Patterns
│ ├── ASPNetCore.CleanArchitecture.Patterns.csproj
│ └── Specification
│ │ ├── IdentitySpecification.cs
│ │ ├── GenericSpecification.cs
│ │ ├── NotSpecification.cs
│ │ ├── OrSpecification.cs
│ │ ├── AndSpecification.cs
│ │ └── AbstractSpecification.cs
├── ASPNetCore.CleanArchitecture.Data
│ ├── Entities
│ │ ├── OrderProduct.cs
│ │ ├── Order.cs
│ │ ├── Product.cs
│ │ └── Customer.cs
│ ├── Database
│ │ ├── AppDbContext.cs
│ │ ├── BaseDbContext.cs
│ │ └── FakeDbContext.cs
│ └── ASPNetCore.CleanArchitecture.Data.csproj
├── ASPNetCore.CleanArchitecture.Domain
│ ├── ASPNetCore.CleanArchitecture.Domain.csproj
│ └── Services
│ │ ├── OrderService.cs
│ │ ├── ProductService.cs
│ │ ├── CustomerService.cs
│ │ └── BaseService.cs
├── ASPNetCore.CleanArchitecture.Resources
│ ├── ASPNetCore.CleanArchitecture.Resources.csproj
│ ├── AppResources.Designer.cs
│ ├── AppResources.resx
│ ├── AppResources.en-US.resx
│ └── AppResources.fr-FR.resx
├── ASPNetCore.CleanArchitecture.Infrastructure
│ ├── Mapping
│ │ └── InfrastructureProfile.cs
│ ├── Repositories
│ │ ├── OrderRepository.cs
│ │ ├── ProductRepository.cs
│ │ ├── CustomerRepository.cs
│ │ ├── GenericRepository.cs
│ │ └── BaseRepository.cs
│ └── ASPNetCore.CleanArchitecture.Infrastructure.csproj
└── ASPNetCore.CleanArchitecture.Setup
│ ├── ASPNetCore.CleanArchitecture.Setup.csproj
│ ├── DependenciesInjector.cs
│ └── StartupExtension.cs
├── README.md
├── .gitattributes
├── .gitignore
└── ASPNetCore.CleanArchitecture.sln
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Api/appsettings.Development.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Debug",
5 | "System": "Information",
6 | "Microsoft": "Information"
7 | }
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Models/ASPNetCore.CleanArchitecture.Models.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netcoreapp3.0
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Api/appsettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Warning",
5 | "System": "Information",
6 | "Micrsoft": "Information"
7 | }
8 | },
9 | "AllowedHosts": "*"
10 | }
11 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Interfaces/IInjectable .cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | namespace ASPNetCore.CleanArchitecture.Interfaces
7 | {
8 | public interface IInjectable
9 | {
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Exceptions/ASPNetCore.CleanArchitecture.Exceptions.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.1
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Patterns/ASPNetCore.CleanArchitecture.Patterns.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.1
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Patterns/Specification/IdentitySpecification.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Linq.Expressions;
3 |
4 | namespace ASPNetCore.CleanArchitecture.Patterns.Specification
5 | {
6 | internal sealed class IdentitySpecification : AbstractSpecification
7 | {
8 | public override Expression> ToExpression()
9 | {
10 | return x => true;
11 | }
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Interfaces/IServices/IOrderService.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using ASPNetCore.CleanArchitecture.Models;
7 |
8 | namespace ASPNetCore.CleanArchitecture.Interfaces.IServices
9 | {
10 | public interface IOrderService : IBaseService, IInjectable
11 | {
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Interfaces/IServices/ICustomerService.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using ASPNetCore.CleanArchitecture.Models;
7 |
8 | namespace ASPNetCore.CleanArchitecture.Interfaces.IServices
9 | {
10 | public interface ICustomerService : IBaseService, IInjectable
11 | {
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Interfaces/IServices/IProductService.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using ASPNetCore.CleanArchitecture.Models;
7 |
8 | namespace ASPNetCore.CleanArchitecture.Interfaces.IServices
9 | {
10 | public interface IProductService : IBaseService, IInjectable
11 | {
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Interfaces/IRepositories/IOrderRepository.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using ASPNetCore.CleanArchitecture.Models;
7 |
8 | namespace ASPNetCore.CleanArchitecture.Interfaces.IRepositories
9 | {
10 | public interface IOrderRepository : IBaseRepository, IInjectable
11 | {
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Api/Controllers/QueriesParams/BaseQueryParams/IBaseQueryParams.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | namespace ASPNetCore.CleanArchitecture.Api.Controllers.QueriesParams.BaseQueryParams
7 | {
8 | public interface IBaseQueryParams : IPagingQueryParams, ISearchQueryParams, ISortQueryParams
9 | {
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Api/Controllers/QueriesParams/BaseQueryParams/ISortOrder.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | namespace ASPNetCore.CleanArchitecture.Api.Controllers.QueriesParams.BaseQueryParams
7 | {
8 | public enum ISortOrder
9 | {
10 | None = 0,
11 | Ascending = 1,
12 | Descending = 2
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Interfaces/IRepositories/IProductRepository.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using ASPNetCore.CleanArchitecture.Models;
7 |
8 | namespace ASPNetCore.CleanArchitecture.Interfaces.IRepositories
9 | {
10 | public interface IProductRepository : IBaseRepository, IInjectable
11 | {
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Interfaces/IRepositories/ICustomerRepository.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using ASPNetCore.CleanArchitecture.Models;
7 |
8 | namespace ASPNetCore.CleanArchitecture.Interfaces.IRepositories
9 | {
10 | public interface ICustomerRepository : IBaseRepository, IInjectable
11 | {
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Interfaces/ASPNetCore.CleanArchitecture.Interfaces.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netcoreapp3.0
5 |
6 |
7 |
8 |
9 | ASPNetCore.CleanArchitecture.Models
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Api/Controllers/QueriesParams/IProductQueryParams.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using ASPNetCore.CleanArchitecture.Api.Controllers.QueriesParams.BaseQueryParams;
7 |
8 | namespace ASPNetCore.CleanArchitecture.Api.Controllers.QueriesParams
9 | {
10 | public interface IProductQueryParams : IBaseQueryParams
11 | {
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Exceptions/AppException.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using System;
7 |
8 | namespace ASPNetCore.CleanArchitecture.Exceptions
9 | {
10 | public class AppException : Exception
11 | {
12 | #region Constructor
13 | public AppException(ExceptionsCodes exceptionCode) : base(((int)exceptionCode).ToString()) { }
14 | #endregion
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Data/Entities/OrderProduct.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using System;
7 |
8 | namespace ASPNetCore.CleanArchitecture.Data.Entities
9 | {
10 | public class OrderProduct
11 | {
12 | public Guid OrderId { get; set; }
13 | public Order Order { get; set; }
14 |
15 | public Guid ProductId { get; set; }
16 | public Product Product { get; set; }
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Api/Controllers/QueriesParams/BaseQueryParams/IPagingQueryParams.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using Microsoft.AspNetCore.Mvc;
7 |
8 | namespace ASPNetCore.CleanArchitecture.Api.Controllers.QueriesParams.BaseQueryParams
9 | {
10 | public interface IPagingQueryParams
11 | {
12 | [FromQuery]
13 | public int Page { get; set; }
14 | [FromQuery]
15 | public int PageSize { get; set; }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Api/Controllers/QueriesParams/BaseQueryParams/ISearchQueryParams.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using Microsoft.AspNetCore.Mvc;
7 |
8 | namespace ASPNetCore.CleanArchitecture.Api.Controllers.QueriesParams.BaseQueryParams
9 | {
10 | public interface ISearchQueryParams
11 | {
12 | [FromQuery]
13 | public string Term { get; set; }
14 | [FromQuery]
15 | public string SearchBy { get; set; }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Api/Controllers/QueriesParams/BaseQueryParams/ISortQueryParams.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using Microsoft.AspNetCore.Mvc;
7 |
8 | namespace ASPNetCore.CleanArchitecture.Api.Controllers.QueriesParams.BaseQueryParams
9 | {
10 | public interface ISortQueryParams
11 | {
12 | [FromQuery]
13 | public string SortBy {get; set;}
14 | [FromQuery]
15 | public ISortOrder SortOrder { get; set; }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Data/Database/AppDbContext.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using Microsoft.EntityFrameworkCore;
7 |
8 | namespace ASPNetCore.CleanArchitecture.Data.Database
9 | {
10 | public class AppDbContext : BaseDbContext
11 | {
12 | #region Constructor
13 | public AppDbContext(DbContextOptions options) : base(options)
14 | {
15 | Database.EnsureCreated();
16 | }
17 | #endregion
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Api/nlog.config:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Api/ViewModels/Order/OrderViewModel.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using System;
7 |
8 | namespace ASPNetCore.CleanArchitecture.Api.ViewModels.Order
9 | {
10 | public class OrderViewModel
11 | {
12 | ///
13 | /// Gets or sets the order's id.
14 | ///
15 | public Guid Id { get; set; }
16 |
17 | ///
18 | /// Gets or sets the order's date.
19 | ///
20 | public DateTime Date { get; set; }
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Domain/ASPNetCore.CleanArchitecture.Domain.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netcoreapp3.0
5 |
6 |
7 |
8 |
9 | ASPNetCore.CleanArchitecture.Interfaces
10 |
11 |
12 | ASPNetCore.CleanArchitecture.Models
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Exceptions/ExceptionDetails.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using Newtonsoft.Json;
7 |
8 | namespace ASPNetCore.CleanArchitecture.Exceptions
9 | {
10 | public class ExceptionDetails
11 | {
12 | #region Fields
13 | public int Code { get; set; }
14 | public string Message { get; set; }
15 | #endregion
16 |
17 | #region Methods
18 | public override string ToString()
19 | {
20 | return JsonConvert.SerializeObject(this);
21 | }
22 | #endregion
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Interfaces/IServices/IGenericService.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using System;
7 | using System.Linq;
8 | using System.Threading.Tasks;
9 |
10 | namespace ASPNetCore.CleanArchitecture.Interfaces.IServices
11 | {
12 | public interface IGenericService where TModel : class
13 | {
14 | Task DeleteById(Guid id);
15 | Task Insert(TModel model);
16 | Task Update(TModel model);
17 | Task Delete(TModel model);
18 | IQueryable GetAll();
19 | Task GetById(Guid id);
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Models/OrderModel.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using System;
7 | using ASPNetCore.CleanArchitecture.Models.Attributs;
8 |
9 | namespace ASPNetCore.CleanArchitecture.Models
10 | {
11 | [EntityName(Entity: "Order")]
12 | public class OrderModel
13 | {
14 | ///
15 | /// Gets or sets the order's id.
16 | ///
17 | public Guid Id { get; set; }
18 |
19 | ///
20 | /// Gets or sets the order's date.
21 | ///
22 | public DateTime Date { get; set; }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Api/Program.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using Microsoft.AspNetCore.Hosting;
7 | using Microsoft.Extensions.Hosting;
8 |
9 | namespace ASPNetCore.CleanArchitecture.Api
10 | {
11 | public class Program
12 | {
13 | public static void Main(string[] args)
14 | {
15 | CreateHostBuilder(args).Build().Run();
16 | }
17 |
18 | public static IHostBuilder CreateHostBuilder(string[] args) =>
19 | Host.CreateDefaultBuilder(args)
20 | .ConfigureWebHostDefaults(webBuilder =>
21 | {
22 | webBuilder.UseStartup();
23 | });
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Data/ASPNetCore.CleanArchitecture.Data.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netcoreapp3.0
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 | ASPNetCore.CleanArchitecture.Interfaces
14 |
15 |
16 | ASPNetCore.CleanArchitecture.Models
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Api/Filters/ValidateModelSateAttribute.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using Microsoft.AspNetCore.Mvc;
7 | using Microsoft.AspNetCore.Mvc.Filters;
8 |
9 | namespace ASPNetCore.CleanArchitecture.Api.Filters
10 | {
11 | public class ValidateModelSateAttribute : ActionFilterAttribute
12 | {
13 | #region Methods
14 | public override void OnActionExecuting(ActionExecutingContext context)
15 | {
16 | if (!context.ModelState.IsValid)
17 | {
18 | context.Result = new BadRequestObjectResult(context.ModelState);
19 | }
20 | return;
21 | }
22 | #endregion
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Api/Filters/OpenAPI/RemoveVersionFromParameter.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using System.Linq;
7 | using Microsoft.OpenApi.Models;
8 | using Swashbuckle.AspNetCore.SwaggerGen;
9 |
10 | namespace ASPNetCore.CleanArchitecture.Api.Filters.OpenAPI
11 | {
12 | public class RemoveVersionFromParameter : IOperationFilter
13 | {
14 | #region Methods
15 | public void Apply(OpenApiOperation operation, OperationFilterContext context)
16 | {
17 | var versionParameter = operation.Parameters.Single(p => p.Name == "version");
18 | operation.Parameters.Remove(versionParameter);
19 | }
20 | #endregion
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Models/Attributes/EntityNameAttribute.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using System;
7 |
8 | namespace ASPNetCore.CleanArchitecture.Models.Attributs
9 | {
10 | public class EntityNameAttribute : Attribute
11 | {
12 | #region Fields
13 | private string _entityName;
14 | #endregion
15 |
16 | #region Constructor
17 | public EntityNameAttribute(string Entity)
18 | {
19 | _entityName = Entity;
20 | }
21 | #endregion
22 |
23 | #region Methods
24 | public string GetEntityName()
25 | {
26 | return _entityName;
27 | }
28 | #endregion
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Api/ViewModels/Product/ProductViewModel.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using System;
7 |
8 | namespace ASPNetCore.CleanArchitecture.Api.ViewModels.Product
9 | {
10 | public class ProductViewModel
11 | {
12 | ///
13 | /// Gets or sets the product's id.
14 | ///
15 | public Guid Id { get; set; }
16 |
17 | ///
18 | /// Gets or sets the product's name.
19 | ///
20 | public string Name { get; set; }
21 |
22 | ///
23 | /// Gets or sets the product's price.
24 | ///
25 | public decimal Price { get; set; }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Api/Mapping/ApiProfile.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using ASPNetCore.CleanArchitecture.Models;
7 | using AutoMapper;
8 | using ASPNetCore.CleanArchitecture.Api.ViewModels.Order;
9 | using ASPNetCore.CleanArchitecture.Api.ViewModels.Product;
10 | using ASPNetCore.CleanArchitecture.Api.ViewModels.Customer;
11 |
12 | namespace ASPNetCore.CleanArchitecture.Api.Mapping
13 | {
14 | public class ApiProfile : Profile
15 | {
16 | public ApiProfile()
17 | {
18 | CreateMap().ReverseMap();
19 | CreateMap().ReverseMap();
20 | CreateMap().ReverseMap();
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Resources/ASPNetCore.CleanArchitecture.Resources.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.1
5 |
6 |
7 |
8 |
9 | True
10 | True
11 | AppResources.resx
12 |
13 |
14 |
15 |
16 |
17 | PublicResXFileCodeGenerator
18 |
19 |
20 | PublicResXFileCodeGenerator
21 | AppResources.Designer.cs
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | **AspNetCore.Templates** is a RESTFul ASP.NET Core 3 API project with a clean architecture using best practices and many useful libraries.
2 |
3 | **Link**
4 |
5 | https://marketplace.visualstudio.com/items?itemName=mohamedalinouira.AspNetCoreTemplates
6 |
7 | **ASP.NET Core 3 API Clean Architecture**
8 |
9 | **Demo**
10 |
11 | https://aspnetcore-templates-cleanarchitecture.azurewebsites.net/index.html
12 |
13 |
14 | **Sample**
15 |
16 | https://github.com/medalinouira/ASPNetCore-CleanArchitecture
17 |
18 |
19 | **Structure**
20 |
21 | 
22 |
23 |
24 | Thank you for having taken your time to provide us your valuable feedback !
25 |
26 |
27 | Mohamed Ali NOUIRA
28 |
29 | www.mohamedalinouira.com
30 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Api/Properties/launchSettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "http://json.schemastore.org/launchsettings.json",
3 | "iisSettings": {
4 | "windowsAuthentication": false,
5 | "anonymousAuthentication": true,
6 | "iisExpress": {
7 | "applicationUrl": "http://localhost:49967",
8 | "sslPort": 44326
9 | }
10 | },
11 | "profiles": {
12 | "IIS Express": {
13 | "commandName": "IISExpress",
14 | "launchBrowser": true,
15 | "launchUrl": "",
16 | "environmentVariables": {
17 | "ASPNETCORE_ENVIRONMENT": "Development"
18 | }
19 | },
20 | "Swagger": {
21 | "commandName": "Project",
22 | "launchBrowser": true,
23 | "launchUrl": "",
24 | "applicationUrl": "https://localhost:5001;http://localhost:5000",
25 | "environmentVariables": {
26 | "ASPNETCORE_ENVIRONMENT": "Development"
27 | }
28 | }
29 | }
30 | }
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Exceptions/ExceptionsCodes.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | namespace ASPNetCore.CleanArchitecture.Exceptions
7 | {
8 | public enum ExceptionsCodes
9 | {
10 | #region Unknown
11 | UnknownCodeException = 50000,
12 | #endregion
13 |
14 | #region NotFound
15 | OrderNotFound = 40400,
16 | ProductNotFound = 40401,
17 | CustomerNotFound = 40402,
18 | #endregion
19 |
20 | #region Conflicts
21 | OrderConflict = 40900,
22 | ProductConflict = 40901,
23 | CustomerConflict = 40902,
24 | #endregion
25 |
26 | #region BadRequest
27 | OrderIdRequired = 40000,
28 | ProductIdRequired = 40001,
29 | CustomerIdRequired = 40002,
30 | #endregion
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Patterns/Specification/GenericSpecification.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using System;
7 | using System.Linq.Expressions;
8 |
9 | namespace ASPNetCore.CleanArchitecture.Patterns.Specification
10 | {
11 | public class GenericSpecification
12 | {
13 | #region Fields
14 | private readonly Expression> _expression;
15 | #endregion
16 |
17 | #region Constructor
18 | public GenericSpecification(Expression> _expression)
19 | {
20 | this._expression = _expression;
21 | }
22 | #endregion
23 |
24 | #region Methods
25 | public bool IsSatisfiedBy(T entity)
26 | {
27 | return _expression.Compile().Invoke(entity);
28 | }
29 | #endregion
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Infrastructure/Mapping/InfrastructureProfile.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using ASPNetCore.CleanArchitecture.Models;
7 | using AutoMapper;
8 | using ASPNetCore.CleanArchitecture.Data.Entities;
9 |
10 | namespace ASPNetCore.CleanArchitecture.Infrastructure.Mapping
11 | {
12 | public class InfrastructureProfile : Profile
13 | {
14 | #region Constructor
15 | public InfrastructureProfile()
16 | {
17 | CreateMap().ReverseMap().ForMember(c => c.Orders, config => config.Ignore());
18 | CreateMap().ReverseMap().ForMember(o => o.OrderProducts, config => config.Ignore());
19 | CreateMap().ReverseMap().ForMember(p => p.OrderProducts, config => config.Ignore());
20 | }
21 | #endregion
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Api/Filters/OpenAPI/ReplaceVersionWithExactValueInPath.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using System.Linq;
7 | using Microsoft.OpenApi.Models;
8 | using Swashbuckle.AspNetCore.SwaggerGen;
9 |
10 | namespace ASPNetCore.CleanArchitecture.Api.Filters.OpenAPI
11 | {
12 | public class ReplaceVersionWithExactValueInPath : IDocumentFilter
13 | {
14 | #region Methods
15 | public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
16 | {
17 | var paths = swaggerDoc.Paths.Select(path => new { Key = path.Key.Replace("v{version}", swaggerDoc.Info.Version), path.Value }).ToList();
18 |
19 | swaggerDoc.Paths = new OpenApiPaths();
20 | foreach (var it in paths)
21 | {
22 | swaggerDoc.Paths.Add(it.Key, it.Value);
23 | }
24 | }
25 | #endregion
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Domain/Services/OrderService.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using ASPNetCore.CleanArchitecture.Models;
7 | using ASPNetCore.CleanArchitecture.Interfaces.IServices;
8 | using ASPNetCore.CleanArchitecture.Interfaces.IRepositories;
9 |
10 | namespace ASPNetCore.CleanArchitecture.Domain.Services
11 | {
12 | public class OrderService : BaseService, IOrderService
13 | {
14 | #region Fields
15 | private readonly IOrderRepository _iOrderRepository;
16 | #endregion
17 |
18 | #region Constructor
19 | public OrderService(IOrderRepository _iOrderRepository,
20 | IBaseRepository _ibaseRepository) : base(_ibaseRepository)
21 | {
22 | this._iOrderRepository = _iOrderRepository;
23 | }
24 | #endregion
25 |
26 | #region Methods
27 | #endregion
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Models/ProductModel.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using System;
7 | using ASPNetCore.CleanArchitecture.Models.Attributs;
8 |
9 | namespace ASPNetCore.CleanArchitecture.Models
10 | {
11 | [EntityName(Entity: "Product")]
12 | public class ProductModel
13 | {
14 | ///
15 | /// Gets or sets the product's id.
16 | ///
17 | public Guid Id { get; set; }
18 |
19 | ///
20 | /// Gets or sets the product's name.
21 | ///
22 | public string Name { get; set; }
23 |
24 | ///
25 | /// Gets or sets the product's price.
26 | ///
27 | public decimal Price { get; set; }
28 |
29 | ///
30 | /// Gets or sets the product's price unit.
31 | ///
32 | public string Unit { get; set; }
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Infrastructure/Repositories/OrderRepository.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using ASPNetCore.CleanArchitecture.Models;
7 | using AutoMapper;
8 | using ASPNetCore.CleanArchitecture.Data.Database;
9 | using ASPNetCore.CleanArchitecture.Interfaces.IRepositories;
10 |
11 | namespace ASPNetCore.CleanArchitecture.Infrastructure.Repositories
12 | {
13 | public class OrderRepository : BaseRepository, IOrderRepository
14 | {
15 | #region Fields
16 | private readonly IMapper _iMapper;
17 | private readonly BaseDbContext _dbContext;
18 | #endregion
19 |
20 | #region Constructor
21 | public OrderRepository(IMapper _iMapper,
22 | BaseDbContext _dbContext) : base(_iMapper, _dbContext)
23 | {
24 | this._iMapper = _iMapper;
25 | this._dbContext = _dbContext;
26 | }
27 | #endregion
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Domain/Services/ProductService.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using ASPNetCore.CleanArchitecture.Models;
7 | using ASPNetCore.CleanArchitecture.Interfaces.IServices;
8 | using ASPNetCore.CleanArchitecture.Interfaces.IRepositories;
9 |
10 | namespace ASPNetCore.CleanArchitecture.Domain.Services
11 | {
12 | public class ProductService : BaseService, IProductService
13 | {
14 | #region Fields
15 | private readonly IProductRepository _iProductRepository;
16 | #endregion
17 |
18 | #region Constructor
19 | public ProductService(IProductRepository _iProductRepository,
20 | IBaseRepository _ibaseRepository) : base(_ibaseRepository)
21 | {
22 | this._iProductRepository = _iProductRepository;
23 | }
24 | #endregion
25 |
26 | #region Methods
27 | #endregion
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Infrastructure/Repositories/ProductRepository.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using ASPNetCore.CleanArchitecture.Models;
7 | using AutoMapper;
8 | using ASPNetCore.CleanArchitecture.Data.Database;
9 | using ASPNetCore.CleanArchitecture.Interfaces.IRepositories;
10 |
11 | namespace ASPNetCore.CleanArchitecture.Infrastructure.Repositories
12 | {
13 | public class ProductRepository : BaseRepository, IProductRepository
14 | {
15 | #region Fields
16 | private readonly IMapper _iMapper;
17 | private readonly BaseDbContext _dbContext;
18 | #endregion
19 |
20 | #region Constructor
21 | public ProductRepository(IMapper _iMapper,
22 | BaseDbContext _dbContext) : base(_iMapper, _dbContext)
23 | {
24 | this._iMapper = _iMapper;
25 | this._dbContext = _dbContext;
26 | }
27 | #endregion
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Infrastructure/Repositories/CustomerRepository.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using ASPNetCore.CleanArchitecture.Models;
7 | using AutoMapper;
8 | using ASPNetCore.CleanArchitecture.Data.Database;
9 | using ASPNetCore.CleanArchitecture.Interfaces.IRepositories;
10 |
11 | namespace ASPNetCore.CleanArchitecture.Infrastructure.Repositories
12 | {
13 | public class CustomerRepository : BaseRepository, ICustomerRepository
14 | {
15 | #region Fields
16 | private readonly IMapper _iMapper;
17 | private readonly BaseDbContext _dbContext;
18 | #endregion
19 |
20 | #region Constructor
21 | public CustomerRepository(IMapper _iMapper,
22 | BaseDbContext _dbContext) : base(_iMapper, _dbContext)
23 | {
24 | this._iMapper = _iMapper;
25 | this._dbContext = _dbContext;
26 | }
27 | #endregion
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Domain/Services/CustomerService.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using ASPNetCore.CleanArchitecture.Models;
7 | using ASPNetCore.CleanArchitecture.Interfaces.IServices;
8 | using ASPNetCore.CleanArchitecture.Interfaces.IRepositories;
9 |
10 | namespace ASPNetCore.CleanArchitecture.Domain.Services
11 | {
12 | public class CustomerService : BaseService, ICustomerService
13 | {
14 | #region Fields
15 | private readonly ICustomerRepository _iCustomerRepository;
16 | #endregion
17 |
18 | #region Constructor
19 | public CustomerService(ICustomerRepository _iCustomerRepository,
20 | IBaseRepository _ibaseRepository) : base(_ibaseRepository)
21 | {
22 | this._iCustomerRepository = _iCustomerRepository;
23 | }
24 | #endregion
25 |
26 | #region Methods
27 | #endregion
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Infrastructure/ASPNetCore.CleanArchitecture.Infrastructure.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netcoreapp3.0
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 | ASPNetCore.CleanArchitecture.Data
16 |
17 |
18 | ASPNetCore.CleanArchitecture.Interfaces
19 |
20 |
21 | ASPNetCore.CleanArchitecture.Models
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Data/Entities/Order.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using System;
7 | using System.Collections.Generic;
8 | using System.ComponentModel.DataAnnotations;
9 | using System.ComponentModel.DataAnnotations.Schema;
10 |
11 | namespace ASPNetCore.CleanArchitecture.Data.Entities
12 | {
13 | public class Order
14 | {
15 | ///
16 | /// Gets or sets the order's id.
17 | ///
18 | [Key]
19 | [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
20 | public Guid Id { get; set; }
21 |
22 | ///
23 | /// Gets or sets the order's date.
24 | ///
25 | public DateTime Date { get; set; }
26 |
27 | ///
28 | /// Gets or sets the order's customer.
29 | ///
30 | public Customer Customer { get; set; }
31 |
32 | ///
33 | /// Many to Many between Order and Product.
34 | ///
35 | public ICollection OrderProducts { get; set; }
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Api/Extensions/ControllerBaseExtensions.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using Microsoft.AspNetCore.Mvc;
7 |
8 | namespace ASPNetCore.CleanArchitecture.Api.Extensions
9 | {
10 | public static class ControllerBaseExtensions
11 | {
12 | #region Methods
13 | public static string GetActionName(this ControllerBase baseController)
14 | {
15 | var routeDateValues = baseController.RouteData.Values;
16 | if (routeDateValues.ContainsKey("action"))
17 | {
18 | return (string)routeDateValues["action"];
19 | }
20 | return string.Empty;
21 | }
22 | public static string GetControllerName(this ControllerBase baseController)
23 | {
24 | var routeDateValues = baseController.RouteData.Values;
25 | if (routeDateValues.ContainsKey("controller"))
26 | {
27 | return (string)routeDateValues["controller"];
28 | }
29 | return string.Empty;
30 | }
31 | #endregion
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Setup/ASPNetCore.CleanArchitecture.Setup.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netcoreapp3.0
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 | ASPNetCore.CleanArchitecture.Interfaces
14 |
15 |
16 | ASPNetCore.CleanArchitecture.Models
17 |
18 |
19 | ASPNetCore.CleanArchitecture.Domain
20 |
21 |
22 | ASPNetCore.CleanArchitecture.Infrastructure
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Patterns/Specification/NotSpecification.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using System;
7 | using System.Linq;
8 | using System.Linq.Expressions;
9 |
10 | namespace ASPNetCore.CleanArchitecture.Patterns.Specification
11 | {
12 | internal sealed class NotSpecification : AbstractSpecification
13 | {
14 | #region Fields
15 | private readonly AbstractSpecification _specification;
16 | #endregion
17 |
18 | #region Constructor
19 | public NotSpecification(AbstractSpecification _specification)
20 | {
21 | this._specification = _specification;
22 | }
23 | #endregion
24 |
25 | #region Methods
26 | public override Expression> ToExpression()
27 | {
28 | Expression> _expression = _specification.ToExpression();
29 |
30 | UnaryExpression notExpression = Expression.Not(_expression.Body);
31 | return Expression.Lambda>(notExpression, _expression.Parameters.Single());
32 | }
33 | #endregion
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Api/ViewModels/Customer/CustomerViewModel.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using System;
7 |
8 | namespace ASPNetCore.CleanArchitecture.Api.ViewModels.Customer
9 | {
10 | public class CustomerViewModel
11 | {
12 | ///
13 | /// Gets or sets the customer's id.
14 | ///
15 | public Guid Id { get; set; }
16 |
17 | ///
18 | /// Gets or sets the customer's first name.
19 | ///
20 | public string FirstName { get; set; }
21 |
22 | ///
23 | /// Gets or sets the customer's last name.
24 | ///
25 | public string LastName { get; set; }
26 |
27 | ///
28 | /// Gets or sets the customer's company.
29 | ///
30 | public string Company { get; set; }
31 |
32 | ///
33 | /// Gets or sets the customer's email.
34 | ///
35 | public string Email { get; set; }
36 |
37 | ///
38 | /// Gets or sets the customer's phone number.
39 | ///
40 | public string Phone { get; set; }
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Data/Entities/Product.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using System;
7 | using System.Collections.Generic;
8 | using System.ComponentModel.DataAnnotations;
9 | using System.ComponentModel.DataAnnotations.Schema;
10 |
11 | namespace ASPNetCore.CleanArchitecture.Data.Entities
12 | {
13 | public class Product
14 | {
15 | ///
16 | /// Gets or sets the product's id.
17 | ///
18 | [Key]
19 | [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
20 | public Guid Id { get; set; }
21 |
22 | ///
23 | /// Gets or sets the product's name.
24 | ///
25 | public string Name { get; set; }
26 |
27 | ///
28 | /// Gets or sets the product's price.
29 | ///
30 | public decimal Price { get; set; }
31 |
32 | ///
33 | /// Gets or sets the product's price unit.
34 | ///
35 | public string Unit { get; set; }
36 |
37 | ///
38 | /// Many to Many between Order and Product.
39 | ///
40 | public ICollection OrderProducts { get; set; }
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Models/CustomerModel.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using System;
7 | using ASPNetCore.CleanArchitecture.Models.Attributs;
8 |
9 | namespace ASPNetCore.CleanArchitecture.Models
10 | {
11 | [EntityName(Entity: "Customer")]
12 | public class CustomerModel
13 | {
14 | ///
15 | /// Gets or sets the customer's id.
16 | ///
17 | public Guid Id { get; set; }
18 |
19 | ///
20 | /// Gets or sets the customer's first name.
21 | ///
22 | public string FirstName { get; set; }
23 |
24 | ///
25 | /// Gets or sets the customer's last name.
26 | ///
27 | public string LastName { get; set; }
28 |
29 | ///
30 | /// Gets or sets the customer's company.
31 | ///
32 | public string Company { get; set; }
33 |
34 | ///
35 | /// Gets or sets the customer's email.
36 | ///
37 | public string Email { get; set; }
38 |
39 | ///
40 | /// Gets or sets the customer's phone number.
41 | ///
42 | public string Phone { get; set; }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Interfaces/IServices/IBaseService.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using System;
7 | using System.Threading.Tasks;
8 | using System.Linq.Expressions;
9 | using System.Collections.Generic;
10 |
11 | namespace ASPNetCore.CleanArchitecture.Interfaces.IServices
12 | {
13 | public interface IBaseService
14 | where TModel : class
15 | {
16 | #region Get
17 | TModel GetById(object id);
18 | Task GetByIdAsync(object id);
19 | IList GetAll();
20 | Task> GetAllAsync();
21 | #endregion
22 |
23 | #region Add
24 | TModel Add(TModel modelToAdd);
25 | Task AddAsync(TModel modelToAdd);
26 | void AddRange(IList modelsToAdd);
27 | #endregion
28 |
29 | #region Update
30 | void Update(TModel modelToUpdate);
31 | void UpdateRange(IList modelsToUpdate);
32 | #endregion
33 |
34 | #region Delete
35 | void DeleteById(object id);
36 | void Delete(TModel modelToDelete);
37 | void DeleteRange(IList modelsToDelete);
38 | #endregion
39 |
40 | #region Global
41 | bool Exist(Expression> predicate);
42 | #endregion
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Patterns/Specification/OrSpecification.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using System;
7 | using System.Linq;
8 | using System.Linq.Expressions;
9 |
10 | namespace ASPNetCore.CleanArchitecture.Patterns.Specification
11 | {
12 | internal sealed class OrSpecification : AbstractSpecification
13 | {
14 | #region Fields
15 | private readonly AbstractSpecification _left;
16 | private readonly AbstractSpecification _right;
17 | #endregion
18 |
19 | #region Constructor
20 | public OrSpecification(AbstractSpecification _left, AbstractSpecification _right)
21 | {
22 | this._left = _left;
23 | this._right = _right;
24 | }
25 | #endregion
26 |
27 | #region Methods
28 | public override Expression> ToExpression()
29 | {
30 | Expression> _leftExpression = _left.ToExpression();
31 | Expression> _rightExpression = _right.ToExpression();
32 |
33 | BinaryExpression orElseExpression = Expression.OrElse(_leftExpression, _rightExpression);
34 | return Expression.Lambda>(orElseExpression, _leftExpression.Parameters.Single());
35 | }
36 | #endregion
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Patterns/Specification/AndSpecification.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using System;
7 | using System.Linq;
8 | using System.Linq.Expressions;
9 |
10 | namespace ASPNetCore.CleanArchitecture.Patterns.Specification
11 | {
12 | internal sealed class AndSpecification : AbstractSpecification
13 | {
14 | #region Fields
15 | private readonly AbstractSpecification _left;
16 | private readonly AbstractSpecification _right;
17 | #endregion
18 |
19 | #region Constructor
20 | public AndSpecification(AbstractSpecification _left,
21 | AbstractSpecification _right)
22 | {
23 | this._left = _left;
24 | this._right = _right;
25 | }
26 | #endregion
27 |
28 | #region Methods
29 | public override Expression> ToExpression()
30 | {
31 | Expression> _leftExpression = _left.ToExpression();
32 | Expression> _rightExpression = _right.ToExpression();
33 |
34 | BinaryExpression andExpression = Expression.AndAlso(_leftExpression, _rightExpression);
35 | return Expression.Lambda>(andExpression, _leftExpression.Parameters.Single());
36 | }
37 | #endregion
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Interfaces/IRepositories/IBaseRepository.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using System;
7 | using System.Threading.Tasks;
8 | using System.Linq.Expressions;
9 | using System.Collections.Generic;
10 |
11 | namespace ASPNetCore.CleanArchitecture.Interfaces.IRepositories
12 | {
13 | public interface IBaseRepository where TModel : class
14 | {
15 | #region Get
16 | TModel GetById(object id);
17 | Task GetByIdAsync(object id);
18 | IList GetAll();
19 | Task> GetAllAsync();
20 | #endregion
21 |
22 | #region Add
23 | TModel Add(TModel modelToAdd);
24 | Task AddAsync(TModel modelToAdd);
25 | void AddRange(IList modelsToAdd);
26 | Task AddRangeAsync(IList modelsToAdd);
27 | #endregion
28 |
29 | #region Update
30 | void Update(TModel modelToUpdate);
31 | void UpdateRange(IList modelsToUpdate);
32 | #endregion
33 |
34 | #region Delete
35 | void DeleteById(object id);
36 | void Delete(TModel modelToDelete);
37 | void DeleteRange(IList modelsToDelete);
38 | #endregion
39 |
40 | #region Global
41 | Task SaveChangesAsync();
42 | bool Exist(Expression> predicate);
43 | #endregion
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Interfaces/IRepositories/IGenericRepository.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using System;
7 | using System.Threading.Tasks;
8 | using System.Linq.Expressions;
9 | using System.Collections.Generic;
10 |
11 | namespace ASPNetCore.CleanArchitecture.Interfaces.IRepositories
12 | {
13 | public interface IGenericRepository where TModel : class where TEntity : class
14 | {
15 | #region Get
16 | TModel GetById(object id);
17 | Task GetByIdAsync(object id);
18 | IList GetAll();
19 | Task> GetAllAsync();
20 | #endregion
21 |
22 | #region Add
23 | TModel Add(TModel modelToAdd);
24 | Task AddAsync(TModel modelToAdd);
25 | void AddRange(IList modelsToAdd);
26 | Task AddRangeAsync(IList modelsToAdd);
27 | #endregion
28 |
29 | #region Update
30 | void Update(TModel modelToUpdate);
31 | void UpdateRange(IList modelsToUpdate);
32 | #endregion
33 |
34 | #region Delete
35 | void DeleteById(object id);
36 | void Delete(TModel modelToDelete);
37 | void DeleteRange(IList modelsToDelete);
38 | #endregion
39 |
40 | #region Global
41 | Task SaveChangesAsync();
42 | bool Exist(Expression> predicate);
43 | #endregion
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Data/Database/BaseDbContext.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using ASPNetCore.CleanArchitecture.Data.Entities;
7 | using Microsoft.EntityFrameworkCore;
8 |
9 | namespace ASPNetCore.CleanArchitecture.Data.Database
10 | {
11 | public class BaseDbContext : DbContext
12 | {
13 | #region Constructor
14 | public BaseDbContext(DbContextOptions options) : base(options)
15 | {
16 |
17 | }
18 | #endregion
19 |
20 | #region DbSets
21 | public DbSet Orders { get; set; }
22 | public DbSet Products { get; set; }
23 | public DbSet Customers { get; set; }
24 | #endregion
25 |
26 | #region Methods
27 | protected override void OnModelCreating(ModelBuilder modelBuilder)
28 | {
29 | base.OnModelCreating(modelBuilder);
30 |
31 | //Many To Many between Order and Product
32 | modelBuilder.Entity()
33 | .HasKey(op => new { op.OrderId, op.ProductId });
34 |
35 | modelBuilder.Entity()
36 | .HasOne(op => op.Product)
37 | .WithMany(op => op.OrderProducts)
38 | .HasForeignKey(op => op.ProductId);
39 |
40 | modelBuilder.Entity()
41 | .HasOne(op => op.Order)
42 | .WithMany(op => op.OrderProducts)
43 | .HasForeignKey(op => op.OrderId);
44 | }
45 | #endregion
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Data/Entities/Customer.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using System;
7 | using System.Collections.Generic;
8 | using System.ComponentModel.DataAnnotations;
9 | using System.ComponentModel.DataAnnotations.Schema;
10 |
11 | namespace ASPNetCore.CleanArchitecture.Data.Entities
12 | {
13 | public class Customer
14 | {
15 | ///
16 | /// Gets or sets the customer's id.
17 | ///
18 | [Key]
19 | [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
20 | public Guid Id { get; set; }
21 |
22 | ///
23 | /// Gets or sets the customer's first name.
24 | ///
25 | public string FirstName { get; set; }
26 |
27 | ///
28 | /// Gets or sets the customer's last name.
29 | ///
30 | public string LastName { get; set; }
31 |
32 | ///
33 | /// Gets or sets the customer's company.
34 | ///
35 | public string Company { get; set; }
36 |
37 | ///
38 | /// Gets or sets the customer's email.
39 | ///
40 | public string Email { get; set; }
41 |
42 | ///
43 | /// Gets or sets the customer's phone number.
44 | ///
45 | public string Phone { get; set; }
46 |
47 | ///
48 | /// Gets or sets the customer's orders.
49 | ///
50 | public ICollection Orders { get; set; }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Setup/DependenciesInjector.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using System;
7 | using ASPNetCore.CleanArchitecture.Interfaces;
8 | using System.Linq;
9 | using System.Reflection;
10 | using Microsoft.Extensions.DependencyInjection;
11 |
12 | namespace ASPNetCore.CleanArchitecture.Setup
13 | {
14 | public static class DependenciesInjector
15 | {
16 | #region Methods
17 | public static void AddIInjectableDependencies(this IServiceCollection services, Type ObjectType)
18 | {
19 | var types = (from t in ObjectType.Assembly.GetTypes()
20 | where t.GetTypeInfo().IsClass && !t.GetTypeInfo().IsAbstract && t.GetTypeInfo().ImplementedInterfaces.Any(i => i == typeof(IInjectable))
21 | select (t)).OrderBy(p => p.Name).ToList();
22 |
23 | foreach (var type in types)
24 | {
25 | int max = 0;
26 | Type interfaceType = null;
27 | foreach (var it in type.GetInterfaces())
28 | {
29 | int nombreInterfaceImplIService = it.GetInterfaces().Length;
30 | if (it.GetInterfaces().Any(i => i == typeof(IInjectable)) && max < nombreInterfaceImplIService)
31 | {
32 | max = nombreInterfaceImplIService;
33 | interfaceType = it;
34 | }
35 | }
36 | services.AddTransient(interfaceType, type);
37 | }
38 | }
39 | #endregion
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Patterns/Specification/AbstractSpecification.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using System;
7 | using System.Linq.Expressions;
8 |
9 | namespace ASPNetCore.CleanArchitecture.Patterns.Specification
10 | {
11 | public abstract class AbstractSpecification
12 | {
13 | #region Fields
14 | public static readonly AbstractSpecification All = new IdentitySpecification();
15 | public abstract Expression> ToExpression();
16 | #endregion
17 |
18 | #region Methods
19 | public bool IsSatisfiedBy(T entity)
20 | {
21 | Func predicate = ToExpression().Compile();
22 | return predicate(entity);
23 | }
24 | public AbstractSpecification And(AbstractSpecification specification)
25 | {
26 | if (this == All)
27 | {
28 | return specification;
29 | }
30 | if (specification == All)
31 | {
32 | return this;
33 | }
34 | return new AndSpecification(this, specification);
35 | }
36 | public AbstractSpecification Or(AbstractSpecification specification)
37 | {
38 | if (this == All || specification == All)
39 | {
40 | return All;
41 | }
42 | return new OrSpecification(this, specification);
43 | }
44 | public AbstractSpecification Not()
45 | {
46 | return new NotSpecification(this);
47 | }
48 | #endregion
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Setup/StartupExtension.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using System;
7 | using ASPNetCore.CleanArchitecture.Data.Database;
8 | using ASPNetCore.CleanArchitecture.Domain.Services;
9 | using ASPNetCore.CleanArchitecture.Interfaces.IServices;
10 | using ASPNetCore.CleanArchitecture.Interfaces.IRepositories;
11 | using ASPNetCore.CleanArchitecture.Infrastructure.Repositories;
12 | using Microsoft.EntityFrameworkCore;
13 | using Microsoft.Extensions.DependencyInjection;
14 |
15 | namespace ASPNetCore.CleanArchitecture.Setup
16 | {
17 | public static class StartupExtension
18 | {
19 | #region Methods
20 | public static IServiceCollection AddAppDependencies(this IServiceCollection _iServiceCollection)
21 | {
22 | #region Data
23 | _iServiceCollection.AddDbContext(opt => opt.UseInMemoryDatabase(Guid.NewGuid().ToString()));
24 | #endregion
25 |
26 | #region Services
27 | _iServiceCollection.AddIInjectableDependencies(typeof(OrderService));
28 | _iServiceCollection.AddTransient(typeof(IBaseService<>), typeof(BaseService<>));
29 | #endregion
30 |
31 | #region Repositories
32 | _iServiceCollection.AddIInjectableDependencies(typeof(OrderRepository));
33 | _iServiceCollection.AddTransient(typeof(IBaseRepository<>), typeof(BaseRepository<>));
34 | _iServiceCollection.AddTransient(typeof(IGenericRepository<,>), typeof(GenericRepository<,>));
35 | #endregion
36 |
37 | return _iServiceCollection;
38 | }
39 | #endregion
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Api/Extensions/ApplicationBuilderExtensions.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using ASPNetCore.CleanArchitecture.Api.Middlewares;
7 | using Microsoft.AspNetCore.Builder;
8 | using Swashbuckle.AspNetCore.SwaggerUI;
9 |
10 | namespace ASPNetCore.CleanArchitecture.Api.Extensions
11 | {
12 | public static class ApplicationBuilderExtensions
13 | {
14 | #region Methods
15 | public static IApplicationBuilder UseAppSwagger(this IApplicationBuilder _iApplicationBuilder)
16 | {
17 | // Enable middleware to serve generated Swagger as a JSON endpoint.
18 | _iApplicationBuilder.UseSwagger();
19 |
20 | // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
21 | // specifying the Swagger JSON endpoint.
22 | _iApplicationBuilder.UseSwaggerUI(c =>
23 | {
24 | c.EnableFilter();
25 | c.ShowExtensions();
26 | c.EnableValidator();
27 | c.EnableDeepLinking();
28 | c.DisplayOperationId();
29 | c.DisplayRequestDuration();
30 | c.RoutePrefix = string.Empty;
31 | c.DefaultModelExpandDepth(2);
32 | c.DefaultModelsExpandDepth(-1);
33 | c.DocExpansion(DocExpansion.None);
34 | c.DefaultModelRendering(ModelRendering.Model);
35 | c.SwaggerEndpoint($"/swagger/v2.0/swagger.json", "Version 2.0");
36 | c.SwaggerEndpoint($"/swagger/v3.0/swagger.json", "Version 3.0 - beta");
37 | });
38 |
39 | return _iApplicationBuilder;
40 | }
41 | public static IApplicationBuilder UseAppExceptionsMiddleware(this IApplicationBuilder _iApplicationBuilder)
42 | {
43 | _iApplicationBuilder.UseMiddleware();
44 | return _iApplicationBuilder;
45 | }
46 | #endregion
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Api/ASPNetCore.CleanArchitecture.Api.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netcoreapp3.0
5 | ..\docker-compose.dcproj
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 | ASPNetCore.CleanArchitecture.Exceptions
25 |
26 |
27 | ASPNetCore.CleanArchitecture.Interfaces
28 |
29 |
30 | ASPNetCore.CleanArchitecture.Models
31 |
32 |
33 | ASPNetCore.CleanArchitecture.Patterns
34 |
35 |
36 | ASPNetCore.CleanArchitecture.Resources
37 |
38 |
39 | ASPNetCore.CleanArchitecture.Setup
40 |
41 |
42 |
43 |
44 | true
45 | $(NoWarn);1591
46 | d76a6c22-43eb-459a-9cee-afe4495b9bac
47 |
48 |
49 |
50 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # Set default behavior to automatically normalize line endings.
3 | ###############################################################################
4 | * text=auto
5 |
6 | ###############################################################################
7 | # Set default behavior for command prompt diff.
8 | #
9 | # This is need for earlier builds of msysgit that does not have it on by
10 | # default for csharp files.
11 | # Note: This is only used by command line
12 | ###############################################################################
13 | #*.cs diff=csharp
14 |
15 | ###############################################################################
16 | # Set the merge driver for project and solution files
17 | #
18 | # Merging from the command prompt will add diff markers to the files if there
19 | # are conflicts (Merging from VS is not affected by the settings below, in VS
20 | # the diff markers are never inserted). Diff markers may cause the following
21 | # file extensions to fail to load in VS. An alternative would be to treat
22 | # these files as binary and thus will always conflict and require user
23 | # intervention with every merge. To do so, just uncomment the entries below
24 | ###############################################################################
25 | #*.sln merge=binary
26 | #*.csproj merge=binary
27 | #*.vbproj merge=binary
28 | #*.vcxproj merge=binary
29 | #*.vcproj merge=binary
30 | #*.dbproj merge=binary
31 | #*.fsproj merge=binary
32 | #*.lsproj merge=binary
33 | #*.wixproj merge=binary
34 | #*.modelproj merge=binary
35 | #*.sqlproj merge=binary
36 | #*.wwaproj merge=binary
37 |
38 | ###############################################################################
39 | # behavior for image files
40 | #
41 | # image files are treated as binary by default.
42 | ###############################################################################
43 | #*.jpg binary
44 | #*.png binary
45 | #*.gif binary
46 |
47 | ###############################################################################
48 | # diff behavior for common document formats
49 | #
50 | # Convert binary document formats to text before diffing them. This feature
51 | # is only available from the command line. Turn it on by uncommenting the
52 | # entries below.
53 | ###############################################################################
54 | #*.doc diff=astextplain
55 | #*.DOC diff=astextplain
56 | #*.docx diff=astextplain
57 | #*.DOCX diff=astextplain
58 | #*.dot diff=astextplain
59 | #*.DOT diff=astextplain
60 | #*.pdf diff=astextplain
61 | #*.PDF diff=astextplain
62 | #*.rtf diff=astextplain
63 | #*.RTF diff=astextplain
64 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Api/Middlewares/AppExceptionsMiddleware.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using System;
7 | using ASPNetCore.CleanArchitecture.Resources;
8 | using ASPNetCore.CleanArchitecture.Exceptions;
9 | using System.Threading.Tasks;
10 | using Microsoft.AspNetCore.Http;
11 | using Microsoft.Extensions.Logging;
12 | using Microsoft.Extensions.Localization;
13 |
14 | namespace ASPNetCore.CleanArchitecture.Api.Middlewares
15 | {
16 | public class AppExceptionsMiddleware
17 | {
18 | #region Fields
19 | private readonly RequestDelegate _requestDelegate;
20 |
21 | private readonly string _contentType = "application/json";
22 |
23 | private readonly ILogger _iLogger;
24 | private readonly IStringLocalizer _iStringLocalizer;
25 | #endregion
26 |
27 | #region Constructor
28 | public AppExceptionsMiddleware(
29 | RequestDelegate _requestDelegate,
30 | ILogger _iLogger,
31 | IStringLocalizer _iStringLocalizer
32 | )
33 | {
34 | this._iLogger = _iLogger;
35 | this._requestDelegate = _requestDelegate;
36 | this._iStringLocalizer = _iStringLocalizer;
37 | }
38 | #endregion
39 |
40 | #region Methods
41 | public async Task InvokeAsync(HttpContext httpContext)
42 | {
43 | try
44 | {
45 | await _requestDelegate(httpContext);
46 | }
47 | catch (Exception ex)
48 | {
49 | await HandleExceptionAsync(httpContext, ex);
50 | }
51 | }
52 | private async Task HandleExceptionAsync(HttpContext context, Exception ex)
53 | {
54 | var exDetails = CreateException(ex);
55 | int.TryParse(exDetails.Code.ToString().Substring(0, 3), out var statusCode);
56 |
57 | context.Response.StatusCode = statusCode;
58 | context.Response.ContentType = _contentType;
59 |
60 | _iLogger.LogError(exDetails.Code, ex, exDetails.ToString());
61 |
62 | await context.Response.WriteAsync(exDetails.ToString());
63 | }
64 | private ExceptionDetails CreateException(Exception ex)
65 | {
66 | var parseSucceded = int.TryParse(ex.Message, out int code);
67 | int exCode = parseSucceded ? code : (int)ExceptionsCodes.UnknownCodeException;
68 | var exDetails = new ExceptionDetails
69 | {
70 | Code = exCode,
71 | Message = _iStringLocalizer["RSX_EXCEPTION_" + exCode.ToString()]
72 | };
73 |
74 | return exDetails;
75 | }
76 | #endregion
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Domain/Services/BaseService.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using System;
7 | using ASPNetCore.CleanArchitecture.Interfaces.IServices;
8 | using System.Threading.Tasks;
9 | using System.Linq.Expressions;
10 | using ASPNetCore.CleanArchitecture.Interfaces.IRepositories;
11 | using System.Collections.Generic;
12 |
13 | namespace ASPNetCore.CleanArchitecture.Domain.Services
14 | {
15 | public class BaseService : IBaseService
16 | where TModel : class
17 | {
18 | #region Fields
19 | private readonly IBaseRepository _iBaseRepository;
20 | #endregion
21 |
22 | #region Constructor
23 | public BaseService(IBaseRepository _iBaseRepository)
24 | {
25 | this._iBaseRepository = _iBaseRepository;
26 | }
27 | #endregion
28 |
29 | #region Methods
30 | public TModel Add(TModel modelToAdd)
31 | {
32 | return _iBaseRepository.Add(modelToAdd);
33 | }
34 |
35 | public async Task AddAsync(TModel modelToAdd)
36 | {
37 | return await _iBaseRepository.AddAsync(modelToAdd);
38 | }
39 |
40 | public void AddRange(IList modelsToAdd)
41 | {
42 | _iBaseRepository.AddRange(modelsToAdd);
43 | }
44 |
45 | public void Delete(TModel modelToDelete)
46 | {
47 | _iBaseRepository.Delete(modelToDelete);
48 | }
49 |
50 | public void DeleteById(object id)
51 | {
52 | _iBaseRepository.DeleteById(id);
53 | }
54 |
55 | public void DeleteRange(IList modelsToDelete)
56 | {
57 | _iBaseRepository.DeleteRange(modelsToDelete);
58 | }
59 |
60 | public bool Exist(Expression> predicate)
61 | {
62 | return _iBaseRepository.Exist(predicate);
63 | }
64 |
65 | public IList GetAll()
66 | {
67 | return _iBaseRepository.GetAll();
68 | }
69 |
70 | public async Task> GetAllAsync()
71 | {
72 | return await _iBaseRepository.GetAllAsync();
73 | }
74 |
75 | public TModel GetById(object id)
76 | {
77 | return _iBaseRepository.GetById(id);
78 | }
79 |
80 | public async Task GetByIdAsync(object id)
81 | {
82 | return await _iBaseRepository.GetByIdAsync(id);
83 | }
84 |
85 | public async Task SaveChangesAsync()
86 | {
87 | return await _iBaseRepository.SaveChangesAsync();
88 | }
89 |
90 | public void Update(TModel modelToUpdate)
91 | {
92 | _iBaseRepository.Update(modelToUpdate);
93 | }
94 |
95 | public void UpdateRange(IList modelsToUpdate)
96 | {
97 | _iBaseRepository.UpdateRange(modelsToUpdate);
98 | }
99 | #endregion
100 | }
101 | }
102 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Resources/AppResources.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // This code was generated by a tool.
4 | // Runtime Version:4.0.30319.42000
5 | //
6 | // Changes to this file may cause incorrect behavior and will be lost if
7 | // the code is regenerated.
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace ASPNetCore.CleanArchitecture.Resources
12 | {
13 | using System;
14 |
15 |
16 | ///
17 | /// A strongly-typed resource class, for looking up localized strings, etc.
18 | ///
19 | // This class was auto-generated by the StronglyTypedResourceBuilder
20 | // class via a tool like ResGen or Visual Studio.
21 | // To add or remove a member, edit your .ResX file then rerun ResGen
22 | // with the /str option, or rebuild your VS project.
23 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
24 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
25 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
26 | public class AppResources
27 | {
28 |
29 | private static global::System.Resources.ResourceManager resourceMan;
30 |
31 | private static global::System.Globalization.CultureInfo resourceCulture;
32 |
33 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
34 | internal AppResources()
35 | {
36 | }
37 |
38 | ///
39 | /// Returns the cached ResourceManager instance used by this class.
40 | ///
41 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
42 | public static global::System.Resources.ResourceManager ResourceManager
43 | {
44 | get
45 | {
46 | if (object.ReferenceEquals(resourceMan, null))
47 | {
48 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ASPNetCore.CleanArchitecture.Resources.AppResources", typeof(AppResources).Assembly);
49 | resourceMan = temp;
50 | }
51 | return resourceMan;
52 | }
53 | }
54 |
55 | ///
56 | /// Overrides the current thread's CurrentUICulture property for all
57 | /// resource lookups using this strongly typed resource class.
58 | ///
59 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
60 | public static global::System.Globalization.CultureInfo Culture
61 | {
62 | get
63 | {
64 | return resourceCulture;
65 | }
66 | set
67 | {
68 | resourceCulture = value;
69 | }
70 | }
71 |
72 | ///
73 | /// Looks up a localized string similar to A problem happened while handling your request.
74 | ///
75 | public static string RSX_EXCEPTION_50000
76 | {
77 | get
78 | {
79 | return ResourceManager.GetString("RSX_EXCEPTION_50000", resourceCulture);
80 | }
81 | }
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Api/Startup.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using ASPNetCore.CleanArchitecture.Setup;
7 | using AutoMapper;
8 | using ASPNetCore.CleanArchitecture.Api.Extensions;
9 | using System.Globalization;
10 | using Microsoft.AspNetCore.Mvc;
11 | using System.Collections.Generic;
12 | using Microsoft.AspNetCore.Builder;
13 | using Microsoft.AspNetCore.Hosting;
14 | using Microsoft.Extensions.Hosting;
15 | using Microsoft.AspNetCore.Localization;
16 | using Microsoft.Extensions.Configuration;
17 | using Microsoft.Extensions.DependencyInjection;
18 |
19 | namespace ASPNetCore.CleanArchitecture.Api
20 | {
21 | public class Startup
22 | {
23 | public Startup(IConfiguration configuration)
24 | {
25 | Configuration = configuration;
26 | }
27 |
28 | public IConfiguration Configuration { get; }
29 |
30 | // This method gets called by the runtime. Use this method to add services to the container.
31 | public void ConfigureServices(IServiceCollection services)
32 | {
33 | services.AddOptions();
34 | services.AddLocalization();
35 |
36 | var configuration = new MapperConfiguration(cfg =>
37 | cfg.AddMaps(new[] {
38 | "ASPNetCore.CleanArchitecture.Api",
39 | "ASPNetCore.CleanArchitecture.Infrastructure"
40 | })
41 | );
42 | IMapper mapper = configuration.CreateMapper();
43 | services.AddSingleton(mapper);
44 |
45 | services.AddAppMVC();
46 | services.AddAppLogging();
47 | services.AddApiVersioning(o =>
48 | {
49 | o.AssumeDefaultVersionWhenUnspecified = true;
50 | o.DefaultApiVersion = new ApiVersion(1, 0);
51 | });
52 | services.AddAppSwaggerGen();
53 | services.AddAppDependencies();
54 | }
55 |
56 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
57 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
58 | {
59 | if (env.IsDevelopment())
60 | {
61 | app.UseDeveloperExceptionPage();
62 | }
63 | else
64 | {
65 | app.UseHsts();
66 | }
67 |
68 | app.UseAppExceptionsMiddleware();
69 | app.UseRequestLocalization(BuildLocalizationOptions());
70 |
71 | app.UseAppSwagger();
72 | app.UseStaticFiles();
73 | app.UseStatusCodePages();
74 | app.UseHttpsRedirection();
75 |
76 | app.UseRouting();
77 | app.UseEndpoints(endpoints =>
78 | {
79 | endpoints.MapControllers();
80 | });
81 | }
82 |
83 | private RequestLocalizationOptions BuildLocalizationOptions()
84 | {
85 | var supportedCultures = new List
86 | {
87 | new CultureInfo("fr-FR"),
88 | new CultureInfo("en-US")
89 | };
90 |
91 | var options = new RequestLocalizationOptions
92 | {
93 | DefaultRequestCulture = new RequestCulture("fr-FR"),
94 | SupportedCultures = supportedCultures,
95 | SupportedUICultures = supportedCultures
96 | };
97 |
98 | return options;
99 | }
100 | }
101 | }
102 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Infrastructure/Repositories/GenericRepository.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using System;
7 | using AutoMapper;
8 | using System.Linq;
9 | using ASPNetCore.CleanArchitecture.Data.Database;
10 | using System.Threading.Tasks;
11 | using System.Linq.Expressions;
12 | using ASPNetCore.CleanArchitecture.Interfaces.IRepositories;
13 | using System.Collections.Generic;
14 | using Microsoft.EntityFrameworkCore;
15 |
16 | namespace ASPNetCore.CleanArchitecture.Infrastructure.Repositories
17 | {
18 | public class GenericRepository : IGenericRepository where TModel : class where TEntity : class
19 | {
20 | #region Fields
21 | private readonly IMapper _iMapper;
22 | private readonly BaseDbContext _baseDbContext;
23 | #endregion
24 |
25 | #region Constructor
26 | public GenericRepository(
27 | IMapper _iMapper,
28 | BaseDbContext _baseDbContext)
29 | {
30 | this._iMapper = _iMapper;
31 | this._baseDbContext = _baseDbContext;
32 | }
33 | #endregion
34 |
35 | #region Methods
36 |
37 | #region Get
38 | public IList GetAll()
39 | {
40 | var result = _baseDbContext.Set().ToList();
41 | return _iMapper.Map>(result);
42 | }
43 | public async Task> GetAllAsync()
44 | {
45 | var result = await _baseDbContext.Set().ToListAsync();
46 | return _iMapper.Map>(result);
47 | }
48 | public TModel GetById(object id)
49 | {
50 | var result = _baseDbContext.Set().Find(id);
51 | return _iMapper.Map(result);
52 | }
53 | public async Task GetByIdAsync(object id)
54 | {
55 | var result = await _baseDbContext.Set().FindAsync(id);
56 | return _iMapper.Map(result);
57 | }
58 | #endregion
59 |
60 | #region Add
61 | public TModel Add(TModel modelToAdd)
62 | {
63 | var entityToAdd = _iMapper.Map(modelToAdd);
64 | var result = _baseDbContext.Add(entityToAdd);
65 | return _iMapper.Map(result.Entity);
66 | }
67 | public async Task AddAsync(TModel modelToAdd)
68 | {
69 | var entityToAdd = _iMapper.Map(modelToAdd);
70 | var result = await _baseDbContext.AddAsync(entityToAdd);
71 | return _iMapper.Map(result.Entity);
72 | }
73 | public void AddRange(IList modelsToAdd)
74 | {
75 | var entitiesToAdd = _iMapper.Map(modelsToAdd);
76 | _baseDbContext.AddRange(entitiesToAdd);
77 | }
78 | public async Task AddRangeAsync(IList modelsToAdd)
79 | {
80 | var entitiesToAdd = _iMapper.Map(modelsToAdd);
81 | await _baseDbContext.AddRangeAsync(entitiesToAdd);
82 | }
83 | #endregion
84 |
85 | #region Update
86 | public void Update(TModel modelToUpdate)
87 | {
88 | var entityToUpdate = _iMapper.Map(modelToUpdate);
89 | _baseDbContext.Update(entityToUpdate);
90 | }
91 | public void UpdateRange(IList modelsToUpdate)
92 | {
93 | var entitiesToUpdate = _iMapper.Map(modelsToUpdate);
94 | _baseDbContext.UpdateRange(entitiesToUpdate);
95 | }
96 | #endregion
97 |
98 | #region Delete
99 | public void DeleteById(object id)
100 | {
101 | var entityToDelete = this.GetById(id);
102 | _baseDbContext.Remove(entityToDelete);
103 | }
104 | public void Delete(TModel modelToDelete)
105 | {
106 | var entityToDelete = _iMapper.Map(modelToDelete);
107 | _baseDbContext.Remove(entityToDelete);
108 | }
109 | public void DeleteRange(IList modelsToDelete)
110 | {
111 | var entitiesToDelete = _iMapper.Map(modelsToDelete);
112 | _baseDbContext.RemoveRange(entitiesToDelete);
113 | }
114 | #endregion
115 |
116 | #region Global
117 | public bool Exist(Expression> predicate)
118 | {
119 | return _baseDbContext.Set().Any(predicate);
120 | }
121 | public async Task SaveChangesAsync()
122 | {
123 | return await _baseDbContext.SaveChangesAsync();
124 | }
125 | public int SaveChanges()
126 | {
127 | return _baseDbContext.SaveChanges();
128 | }
129 | #endregion
130 |
131 | #endregion
132 | }
133 | }
134 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Infrastructure/Repositories/BaseRepository.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using System;
7 | using AutoMapper;
8 | using System.Linq;
9 | using ASPNetCore.CleanArchitecture.Data.Database;
10 | using ASPNetCore.CleanArchitecture.Models.Attributs;
11 | using System.Reflection;
12 | using System.Threading.Tasks;
13 | using System.Linq.Expressions;
14 | using ASPNetCore.CleanArchitecture.Interfaces.IRepositories;
15 | using System.Collections.Generic;
16 |
17 | namespace ASPNetCore.CleanArchitecture.Infrastructure.Repositories
18 | {
19 | public class BaseRepository : IBaseRepository where TModel : class
20 | {
21 | #region Fields
22 | private readonly IMapper _iMapper;
23 | private readonly BaseDbContext _dbContext;
24 | private readonly dynamic _iGenericRepository;
25 | #endregion
26 |
27 | #region Constructor
28 | public BaseRepository(IMapper _iMapper,
29 | BaseDbContext _dbContext)
30 | {
31 | this._iMapper = _iMapper;
32 | this._dbContext = _dbContext;
33 |
34 | _iGenericRepository = InitGenericRepository();
35 | }
36 | #endregion
37 |
38 | #region Methods
39 |
40 | #region Get
41 | public IList GetAll()
42 | {
43 | return _iGenericRepository.GetAll();
44 | }
45 | public async Task> GetAllAsync()
46 | {
47 | return await _iGenericRepository.GetAllAsync();
48 | }
49 | public TModel GetById(object id)
50 | {
51 | return _iGenericRepository.GetById(id);
52 | }
53 | public async Task GetByIdAsync(object id)
54 | {
55 | return await _iGenericRepository.GetByIdAsync(id);
56 | }
57 | #endregion
58 |
59 | #region Add
60 | public TModel Add(TModel modelToAdd)
61 | {
62 | return _iGenericRepository.Add(modelToAdd);
63 | }
64 | public async Task AddAsync(TModel modelToAdd)
65 | {
66 | return await _iGenericRepository.AddAsync(modelToAdd);
67 | }
68 | public void AddRange(IList modelsToAdd)
69 | {
70 | _iGenericRepository.AddRange(modelsToAdd);
71 | }
72 | public async Task AddRangeAsync(IList modelsToAdd)
73 | {
74 | await _iGenericRepository.AddRangeAsync(modelsToAdd);
75 | }
76 | #endregion
77 |
78 | #region Update
79 | public void Update(TModel modelToUpdate)
80 | {
81 | _iGenericRepository.Update(modelToUpdate);
82 | }
83 | public void UpdateRange(IList modelsToUpdate)
84 | {
85 | _iGenericRepository.UpdateRange(modelsToUpdate);
86 | }
87 | #endregion
88 |
89 | #region Delete
90 | public void DeleteById(object id)
91 | {
92 | _iGenericRepository.DeleteById(id);
93 | }
94 | public void Delete(TModel modelToDelete)
95 | {
96 | _iGenericRepository.Delete(modelToDelete);
97 | }
98 | public void DeleteRange(IList modelsToDelete)
99 | {
100 | _iGenericRepository.DeleteRange(modelsToDelete);
101 | }
102 | #endregion
103 |
104 | #region Global
105 | public bool Exist(Expression> predicate)
106 | {
107 | return _iGenericRepository.Exist(predicate);
108 | }
109 | public async Task SaveChangesAsync()
110 | {
111 | return await _iGenericRepository.SaveChangesAsync();
112 | }
113 | public int SaveChanges()
114 | {
115 | return _iGenericRepository.SaveChanges();
116 | }
117 | #endregion
118 |
119 | private dynamic InitGenericRepository()
120 | {
121 | Attribute[] attrs = Attribute.GetCustomAttributes(typeof(TModel));
122 | var entityNameAttr = attrs.Where(attr => attr is EntityNameAttribute).FirstOrDefault() as EntityNameAttribute;
123 | var entityName = entityNameAttr.GetEntityName();
124 |
125 | Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
126 | var entityType = (from elem in (from app in assemblies
127 | select (from tip in app.GetTypes()
128 | where tip.Name == entityName.Trim()
129 | select tip).FirstOrDefault())
130 | where elem != null
131 | select elem).FirstOrDefault();
132 |
133 | Type abstractDAOType = typeof(GenericRepository<,>).MakeGenericType(typeof(TModel), entityType);
134 | return Activator.CreateInstance(abstractDAOType, _iMapper, _dbContext);
135 | }
136 | #endregion
137 | }
138 | }
139 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Data/Database/FakeDbContext.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using System;
7 | using System.Linq;
8 | using ASPNetCore.CleanArchitecture.Data.Entities;
9 | using System.Collections.Generic;
10 | using Microsoft.EntityFrameworkCore;
11 |
12 | namespace ASPNetCore.CleanArchitecture.Data.Database
13 | {
14 | public class FakeDbContext : BaseDbContext
15 | {
16 | #region Constructor
17 | public FakeDbContext(DbContextOptions options) : base(options)
18 | {
19 | SeedFakeData();
20 | }
21 | #endregion
22 |
23 | #region Methods
24 | public void SeedFakeData()
25 | {
26 | //Mock Products
27 | Products.Add(new Product { Id = Guid.NewGuid(), Name = "Product 1", Price = 323, Unit = "euro" });
28 | Products.Add(new Product { Id = Guid.NewGuid(), Name = "Product 2", Price = 400, Unit = "euro" });
29 | Products.Add(new Product { Id = Guid.NewGuid(), Name = "Product 3", Price = 234, Unit = "euro" });
30 | Products.Add(new Product { Id = Guid.NewGuid(), Name = "Product 4", Price = 120, Unit = "euro" });
31 | Products.Add(new Product { Id = Guid.NewGuid(), Name = "Product 5", Price = 850, Unit = "euro" });
32 | Products.Add(new Product { Id = Guid.NewGuid(), Name = "Product 6", Price = 43, Unit = "euro" });
33 | Products.Add(new Product { Id = Guid.NewGuid(), Name = "Product 7", Price = 165, Unit = "euro" });
34 | Products.Add(new Product { Id = Guid.NewGuid(), Name = "Product 8", Price = 549, Unit = "euro" });
35 | SaveChanges();
36 |
37 | //Mock Orders
38 | Orders.Add(new Order { Id = Guid.NewGuid(), Date = DateTime.Now.AddDays(-5) });
39 | Orders.Add(new Order { Id = Guid.NewGuid(), Date = DateTime.Now.AddDays(-10) });
40 | Orders.Add(new Order { Id = Guid.NewGuid(), Date = DateTime.Now.AddDays(-12) });
41 | Orders.Add(new Order { Id = Guid.NewGuid(), Date = DateTime.Now.AddDays(-11) });
42 | Orders.Add(new Order { Id = Guid.NewGuid(), Date = DateTime.Now.AddDays(-2) });
43 | Orders.Add(new Order { Id = Guid.NewGuid(), Date = DateTime.Now.AddDays(-19) });
44 | Orders.Add(new Order { Id = Guid.NewGuid(), Date = DateTime.Now.AddDays(-1) });
45 | Orders.Add(new Order { Id = Guid.NewGuid(), Date = DateTime.Now.AddDays(-15) });
46 | SaveChanges();
47 |
48 | //Mock OrderProducts
49 | OrderProduct orderProduct1 = new OrderProduct() { Order = Orders.ToList()[0], Product = Products.ToList()[0] };
50 | OrderProduct orderProduct2 = new OrderProduct() { Order = Orders.ToList()[0], Product = Products.ToList()[1] };
51 | OrderProduct orderProduct3 = new OrderProduct() { Order = Orders.ToList()[0], Product = Products.ToList()[2] };
52 |
53 | OrderProduct orderProduct4 = new OrderProduct() { Order = Orders.ToList()[1], Product = Products.ToList()[3] };
54 | OrderProduct orderProduct5 = new OrderProduct() { Order = Orders.ToList()[1], Product = Products.ToList()[4] };
55 |
56 | OrderProduct orderProduct6 = new OrderProduct() { Order = Orders.ToList()[2], Product = Products.ToList()[5] };
57 |
58 | OrderProduct orderProduct7 = new OrderProduct() { Order = Orders.ToList()[3], Product = Products.ToList()[6] };
59 |
60 | OrderProduct orderProduct8 = new OrderProduct() { Order = Orders.ToList()[4], Product = Products.ToList()[7] };
61 |
62 | OrderProduct orderProduct9 = new OrderProduct() { Order = Orders.ToList()[5], Product = Products.ToList()[5] };
63 |
64 | OrderProduct orderProduct10 = new OrderProduct() { Order = Orders.ToList()[6], Product = Products.ToList()[2] };
65 |
66 | OrderProduct orderProduct11 = new OrderProduct() { Order = Orders.ToList()[7], Product = Products.ToList()[6] };
67 | SaveChanges();
68 |
69 | //Mock Customers
70 | Customers.Add(new Customer { Id = Guid.NewGuid(), FirstName = "FirstName 1", LastName = "LastName 1", Email = "email1@email.com", Company = "Company 1", Phone = "06 XX XX XX XX", Orders = new List() { } });
71 | Customers.Add(new Customer { Id = Guid.NewGuid(), FirstName = "FirstName 2", LastName = "LastName 2", Email = "email2@email.com", Company = "Company 2", Phone = "07 XX XX XX XX", Orders = new List() { Orders.ToList()[0], Orders.ToList()[1], Orders.ToList()[2] } });
72 | Customers.Add(new Customer { Id = Guid.NewGuid(), FirstName = "FirstName 3", LastName = "LastName 3", Email = "email3@email.com", Company = "Company 3", Phone = "08 XX XX XX XX", Orders = new List() { Orders.ToList()[3], Orders.ToList()[4], Orders.ToList()[5] } });
73 | Customers.Add(new Customer { Id = Guid.NewGuid(), FirstName = "FirstName 4", LastName = "LastName 4", Email = "email4@email.com", Company = "Company 4", Phone = "09 XX XX XX XX", Orders = new List() { Orders.ToList()[6], Orders.ToList()[7] } });
74 | SaveChanges();
75 | }
76 | #endregion
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 |
4 | # User-specific files
5 | *.suo
6 | *.user
7 | *.userosscache
8 | *.sln.docstates
9 |
10 | # User-specific files (MonoDevelop/Xamarin Studio)
11 | *.userprefs
12 |
13 | # Build results
14 | [Dd]ebug/
15 | [Dd]ebugPublic/
16 | [Rr]elease/
17 | [Rr]eleases/
18 | x64/
19 | x86/
20 | bld/
21 | [Bb]in/
22 | [Oo]bj/
23 | [Ll]og/
24 |
25 | # Visual Studio 2015 cache/options directory
26 | .vs/
27 | # Uncomment if you have tasks that create the project's static files in wwwroot
28 | #wwwroot/
29 |
30 | # MSTest test Results
31 | [Tt]est[Rr]esult*/
32 | [Bb]uild[Ll]og.*
33 |
34 | # NUNIT
35 | *.VisualState.xml
36 | TestResult.xml
37 |
38 | # Build Results of an ATL Project
39 | [Dd]ebugPS/
40 | [Rr]eleasePS/
41 | dlldata.c
42 |
43 | # DNX
44 | project.lock.json
45 | project.fragment.lock.json
46 | artifacts/
47 |
48 | *_i.c
49 | *_p.c
50 | *_i.h
51 | *.ilk
52 | *.meta
53 | *.obj
54 | *.pch
55 | *.pdb
56 | *.pgc
57 | *.pgd
58 | *.rsp
59 | *.sbr
60 | *.tlb
61 | *.tli
62 | *.tlh
63 | *.tmp
64 | *.tmp_proj
65 | *.log
66 | *.vspscc
67 | *.vssscc
68 | .builds
69 | *.pidb
70 | *.svclog
71 | *.scc
72 |
73 | # Chutzpah Test files
74 | _Chutzpah*
75 |
76 | # Visual C++ cache files
77 | ipch/
78 | *.aps
79 | *.ncb
80 | *.opendb
81 | *.opensdf
82 | *.sdf
83 | *.cachefile
84 | *.VC.db
85 | *.VC.VC.opendb
86 |
87 | # Visual Studio profiler
88 | *.psess
89 | *.vsp
90 | *.vspx
91 | *.sap
92 |
93 | # TFS 2012 Local Workspace
94 | $tf/
95 |
96 | # Guidance Automation Toolkit
97 | *.gpState
98 |
99 | # ReSharper is a .NET coding add-in
100 | _ReSharper*/
101 | *.[Rr]e[Ss]harper
102 | *.DotSettings.user
103 |
104 | # JustCode is a .NET coding add-in
105 | .JustCode
106 |
107 | # TeamCity is a build add-in
108 | _TeamCity*
109 |
110 | # DotCover is a Code Coverage Tool
111 | *.dotCover
112 |
113 | # NCrunch
114 | _NCrunch_*
115 | .*crunch*.local.xml
116 | nCrunchTemp_*
117 |
118 | # MightyMoose
119 | *.mm.*
120 | AutoTest.Net/
121 |
122 | # Web workbench (sass)
123 | .sass-cache/
124 |
125 | # Installshield output folder
126 | [Ee]xpress/
127 |
128 | # DocProject is a documentation generator add-in
129 | DocProject/buildhelp/
130 | DocProject/Help/*.HxT
131 | DocProject/Help/*.HxC
132 | DocProject/Help/*.hhc
133 | DocProject/Help/*.hhk
134 | DocProject/Help/*.hhp
135 | DocProject/Help/Html2
136 | DocProject/Help/html
137 |
138 | # Click-Once directory
139 | publish/
140 |
141 | # Publish Web Output
142 | *.[Pp]ublish.xml
143 | *.azurePubxml
144 | # TODO: Comment the next line if you want to checkin your web deploy settings
145 | # but database connection strings (with potential passwords) will be unencrypted
146 | #*.pubxml
147 | *.publishproj
148 |
149 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
150 | # checkin your Azure Web App publish settings, but sensitive information contained
151 | # in these scripts will be unencrypted
152 | PublishScripts/
153 |
154 | # NuGet Packages
155 | *.nupkg
156 | # The packages folder can be ignored because of Package Restore
157 | **/packages/*
158 | # except build/, which is used as an MSBuild target.
159 | !**/packages/build/
160 | # Uncomment if necessary however generally it will be regenerated when needed
161 | #!**/packages/repositories.config
162 | # NuGet v3's project.json files produces more ignoreable files
163 | *.nuget.props
164 | *.nuget.targets
165 |
166 | # Microsoft Azure Build Output
167 | csx/
168 | *.build.csdef
169 |
170 | # Microsoft Azure Emulator
171 | ecf/
172 | rcf/
173 |
174 | # Windows Store app package directories and files
175 | AppPackages/
176 | BundleArtifacts/
177 | Package.StoreAssociation.xml
178 | _pkginfo.txt
179 |
180 | # Visual Studio cache files
181 | # files ending in .cache can be ignored
182 | *.[Cc]ache
183 | # but keep track of directories ending in .cache
184 | !*.[Cc]ache/
185 |
186 | # Others
187 | ClientBin/
188 | ~$*
189 | *~
190 | *.dbmdl
191 | *.dbproj.schemaview
192 | *.jfm
193 | *.pfx
194 | *.publishsettings
195 | node_modules/
196 | orleans.codegen.cs
197 |
198 | # Since there are multiple workflows, uncomment next line to ignore bower_components
199 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
200 | #bower_components/
201 |
202 | # RIA/Silverlight projects
203 | Generated_Code/
204 |
205 | # Backup & report files from converting an old project file
206 | # to a newer Visual Studio version. Backup files are not needed,
207 | # because we have git ;-)
208 | _UpgradeReport_Files/
209 | Backup*/
210 | UpgradeLog*.XML
211 | UpgradeLog*.htm
212 |
213 | # SQL Server files
214 | *.mdf
215 | *.ldf
216 |
217 | # Business Intelligence projects
218 | *.rdl.data
219 | *.bim.layout
220 | *.bim_*.settings
221 |
222 | # Microsoft Fakes
223 | FakesAssemblies/
224 |
225 | # GhostDoc plugin setting file
226 | *.GhostDoc.xml
227 |
228 | # Node.js Tools for Visual Studio
229 | .ntvs_analysis.dat
230 |
231 | # Visual Studio 6 build log
232 | *.plg
233 |
234 | # Visual Studio 6 workspace options file
235 | *.opt
236 |
237 | # Visual Studio LightSwitch build output
238 | **/*.HTMLClient/GeneratedArtifacts
239 | **/*.DesktopClient/GeneratedArtifacts
240 | **/*.DesktopClient/ModelManifest.xml
241 | **/*.Server/GeneratedArtifacts
242 | **/*.Server/ModelManifest.xml
243 | _Pvt_Extensions
244 |
245 | # Paket dependency manager
246 | .paket/paket.exe
247 | paket-files/
248 |
249 | # FAKE - F# Make
250 | .fake/
251 |
252 | # JetBrains Rider
253 | .idea/
254 | *.sln.iml
255 |
256 | # CodeRush
257 | .cr/
258 |
259 | # Python Tools for Visual Studio (PTVS)
260 | __pycache__/
261 | *.pyc
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Api/Controllers/OrdersController.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using System;
7 | using ASPNetCore.CleanArchitecture.Models;
8 | using System.Linq;
9 | using ASPNetCore.CleanArchitecture.Api.Filters;
10 | using ASPNetCore.CleanArchitecture.Api.Extensions;
11 | using ASPNetCore.CleanArchitecture.Interfaces.IServices;
12 | using System.Threading.Tasks;
13 | using Microsoft.AspNetCore.Mvc;
14 | using Microsoft.Extensions.Logging;
15 |
16 | namespace ASPNetCore.CleanArchitecture.Api.Controllers
17 | {
18 | [ApiVersion("2.0")]
19 | [ApiVersion("3.0")]
20 | [Route("api/v{version:apiVersion}/[controller]")]
21 | public class OrdersController : Controller
22 | {
23 | #region Fields
24 | private readonly IOrderService _iOrderService;
25 | private readonly ILogger _iLogger;
26 | #endregion
27 |
28 | #region Constructor
29 | public OrdersController(IOrderService _iOrderService,
30 | ILogger _iLogger)
31 | {
32 | this._iLogger = _iLogger;
33 | this._iOrderService = _iOrderService;
34 | }
35 | #endregion
36 |
37 | #region Actions
38 |
39 | #region CRUD
40 | ///
41 | /// Get all orders.
42 | ///
43 | // GET: api/orders
44 | [HttpGet]
45 | [ProducesResponseType(200)]
46 | [ProducesResponseType(204)]
47 | [ProducesResponseType(500)]
48 | public async Task GetAll()
49 | {
50 | _iLogger.LogInformation($"Controller : {this.GetControllerName()} , Action {this.GetActionName()} : => Visited at {DateTime.UtcNow.ToLongTimeString()}");
51 |
52 | var orders = await _iOrderService.GetAllAsync();
53 | if (orders != null && orders.Count() > 0)
54 | {
55 | return Ok(orders);
56 | }
57 | return NoContent();
58 | }
59 |
60 | ///
61 | /// Get order by id.
62 | ///
63 | // GET api/orders
64 | [HttpGet("{id}")]
65 | [ProducesResponseType(200)]
66 | [ProducesResponseType(400)]
67 | [ProducesResponseType(404)]
68 | [ProducesResponseType(500)]
69 | public async Task GetById(Guid id)
70 | {
71 | _iLogger.LogInformation($"Controller : {this.GetControllerName()} , Action {this.GetActionName()} : => Visited at {DateTime.UtcNow.ToLongTimeString()}");
72 |
73 | var order = await _iOrderService.GetByIdAsync(id);
74 | if (order == null)
75 | {
76 | _iLogger.LogInformation($"Order with {id} wasn't found");
77 | return NotFound();
78 | }
79 | return Ok(order);
80 | }
81 |
82 | ///
83 | /// Add a new order.
84 | ///
85 | // POST api/orders
86 | [HttpPost]
87 | [ValidateModelSate]
88 | [ProducesResponseType(201)]
89 | [ProducesResponseType(400)]
90 | [ProducesResponseType(500)]
91 | public async Task Post([FromBody]OrderModel orderModel)
92 | {
93 | _iLogger.LogInformation($"Controller : {this.GetControllerName()} , Action {this.GetActionName()} : => Visited at {DateTime.UtcNow.ToLongTimeString()}");
94 |
95 | var createdOrder = await _iOrderService.AddAsync(orderModel);
96 |
97 | return CreatedAtAction(nameof(GetById), new { id = createdOrder.Id }, createdOrder.Id);
98 | }
99 |
100 | ///
101 | /// Put an order.
102 | ///
103 | // PUT api/orders/386a8d02-c13a-4f98-8edd-27ece9ee0472
104 | [HttpPut("{id}")]
105 | [ValidateModelSate]
106 | [ProducesResponseType(204)]
107 | [ProducesResponseType(400)]
108 | [ProducesResponseType(404)]
109 | [ProducesResponseType(500)]
110 | public async Task Put(Guid id, [FromBody]OrderModel orderModel)
111 | {
112 | _iLogger.LogInformation($"Controller : {this.GetControllerName()} , Action {this.GetActionName()} : => Visited at {DateTime.UtcNow.ToLongTimeString()}");
113 |
114 | if (!(await OrderExists(id)))
115 | {
116 | return NotFound();
117 | }
118 |
119 | _iOrderService.Update(orderModel);
120 |
121 | return NoContent();
122 | }
123 |
124 | ///
125 | /// Delete order by id.
126 | ///
127 | // DELETE api/orders/386a8d02-c13a-4f98-8edd-27ece9ee0472
128 | [HttpDelete("{id}")]
129 | [ProducesResponseType(204)]
130 | [ProducesResponseType(400)]
131 | [ProducesResponseType(404)]
132 | [ProducesResponseType(500)]
133 | public async Task Delete(Guid id)
134 | {
135 | _iLogger.LogInformation($"Controller : {this.GetControllerName()} , Action {this.GetActionName()} : => Visited at {DateTime.UtcNow.ToLongTimeString()}");
136 |
137 | if (!(await OrderExists(id)))
138 | {
139 | return NotFound();
140 | }
141 |
142 | _iOrderService.DeleteById(id);
143 |
144 | return NoContent();
145 | }
146 |
147 | private async Task OrderExists(Guid id)
148 | {
149 | return (await _iOrderService.GetAllAsync()).Any(a => a.Id.Equals(id));
150 | }
151 | #endregion
152 |
153 | #region GLOBAL
154 | #endregion
155 |
156 | #endregion
157 | }
158 | }
159 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Api/Extensions/ServiceCollectionExtensions.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using System;
7 | using System.IO;
8 | using System.Linq;
9 | using System.Reflection;
10 | using ASPNetCore.CleanArchitecture.Api.Filters.OpenAPI;
11 | using NLog.Extensions.Logging;
12 | using Microsoft.OpenApi.Models;
13 | using Microsoft.AspNetCore.Mvc;
14 | using System.Collections.Generic;
15 | using Microsoft.Extensions.Logging;
16 | using Newtonsoft.Json.Serialization;
17 | using Swashbuckle.AspNetCore.SwaggerGen;
18 | using Microsoft.AspNetCore.Mvc.Formatters;
19 | using Microsoft.Extensions.DependencyInjection;
20 |
21 | namespace ASPNetCore.CleanArchitecture.Api.Extensions
22 | {
23 | public static class ServiceCollectionExtensions
24 | {
25 | #region Methods
26 | public static IServiceCollection AddAppMVC(this IServiceCollection _iServiceCollection)
27 | {
28 | _iServiceCollection.AddControllers()
29 | .AddNewtonsoftJson(options =>
30 | {
31 | options.SerializerSettings.ContractResolver = new DefaultContractResolver();
32 |
33 | }).AddMvcOptions(options => {
34 | options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
35 | });
36 | return _iServiceCollection;
37 | }
38 | public static IServiceCollection AddAppLogging(this IServiceCollection _iServiceCollection)
39 | {
40 | _iServiceCollection.AddLogging(loggingBuilder =>
41 | {
42 | loggingBuilder.AddNLog();
43 | loggingBuilder.AddDebug();
44 | loggingBuilder.AddConsole();
45 | });
46 |
47 | return _iServiceCollection;
48 | }
49 | public static IServiceCollection AddAppSwaggerGen(this IServiceCollection _iServiceCollection)
50 | {
51 | _iServiceCollection.AddSwaggerGen(c =>
52 | {
53 | c.DescribeAllEnumsAsStrings();
54 |
55 | c.SwaggerDoc("v2.0", new OpenApiInfo
56 | {
57 | Version = "v2.0",
58 | Title = "ASP.NET Core 3 API Clean Architecture",
59 | Description = "A sample RESTFul ASP.NET Core 3 API",
60 | Contact = new OpenApiContact
61 | {
62 | Name = "Mohamed Ali NOUIRA",
63 | Email = "support@mohamedalinouira.com",
64 | Url = new Uri("https://www.mohamedalinouira.com")
65 | }
66 | });
67 |
68 | c.SwaggerDoc("v3.0", new OpenApiInfo
69 | {
70 | Version = "v3.0",
71 | Title = "ASP.NET Core 3 API Clean Architecture",
72 | Description = "A sample RESTFul ASP.NET Core 3 API",
73 | Contact = new OpenApiContact
74 | {
75 | Name = "Mohamed Ali NOUIRA",
76 | Email = "support@mohamedalinouira.com",
77 | Url = new Uri("https://www.mohamedalinouira.com")
78 | }
79 | });
80 |
81 | c.OperationFilter();
82 | c.DocumentFilter();
83 |
84 | c.DocInclusionPredicate((version, desc) =>
85 | {
86 | if (!desc.TryGetMethodInfo(out MethodInfo methodInfo)) return false;
87 |
88 | var versions = methodInfo.DeclaringType.GetCustomAttributes().OfType()
89 | .SelectMany(attr => attr.Versions);
90 |
91 | var maps = methodInfo.GetCustomAttributes().OfType()
92 | .SelectMany(attr => attr.Versions)
93 | .ToArray();
94 |
95 | var ver = versions.Any(v => $"v{v.ToString()}" == version)
96 | && (!maps.Any() || maps.Any(v => $"v{v.ToString()}" == version));
97 | return ver;
98 | });
99 |
100 | c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
101 | {
102 | Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
103 | Name = "Authorization",
104 | In = ParameterLocation.Header,
105 | Type = SecuritySchemeType.ApiKey,
106 | Scheme = "Bearer"
107 | });
108 |
109 | var security = new OpenApiSecurityRequirement()
110 | {
111 | {
112 | new OpenApiSecurityScheme
113 | {
114 | Reference = new OpenApiReference
115 | {
116 | Type = ReferenceType.SecurityScheme,
117 | Id = "Bearer"
118 | },
119 | Scheme = "oauth2",
120 | Name = "Bearer",
121 | In = ParameterLocation.Header,
122 | },
123 | new List()
124 |
125 | }
126 | };
127 | c.AddSecurityRequirement(security);
128 |
129 | var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
130 | var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
131 | c.IncludeXmlComments(xmlPath);
132 | });
133 |
134 | return _iServiceCollection;
135 | }
136 | #endregion
137 | }
138 | }
139 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Api/Controllers/CustomersController.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using ASPNetCore.CleanArchitecture.Models;
7 | using System;
8 | using System.Linq;
9 | using ASPNetCore.CleanArchitecture.Api.Filters;
10 | using ASPNetCore.CleanArchitecture.Api.Extensions;
11 | using ASPNetCore.CleanArchitecture.Interfaces.IServices;
12 | using System.Threading.Tasks;
13 | using Microsoft.AspNetCore.Mvc;
14 | using Microsoft.Extensions.Logging;
15 |
16 | namespace ASPNetCore.CleanArchitecture.Api.Controllers
17 | {
18 | [ApiVersion("2.0")]
19 | [ApiVersion("3.0")]
20 | [Route("api/v{version:apiVersion}/[controller]")]
21 | public class CustomersController : Controller
22 | {
23 | #region Fields
24 | private readonly ICustomerService _iCustomerService;
25 | private readonly ILogger _iLogger;
26 | #endregion
27 |
28 | #region Constructor
29 | public CustomersController(ICustomerService _iCustomerService,
30 | ILogger _iLogger)
31 | {
32 | this._iLogger = _iLogger;
33 | this._iCustomerService = _iCustomerService;
34 | }
35 | #endregion
36 |
37 | #region Actions
38 |
39 | #region CRUD
40 | ///
41 | /// Get all customers.
42 | ///
43 | // GET: api/customers
44 | [HttpGet]
45 | [ProducesResponseType(200)]
46 | [ProducesResponseType(204)]
47 | [ProducesResponseType(500)]
48 | public async Task GetAll()
49 | {
50 | _iLogger.LogInformation($"Controller : {this.GetControllerName()} , Action {this.GetActionName()} : => Visited at {DateTime.UtcNow.ToLongTimeString()}");
51 |
52 | var customers = await _iCustomerService.GetAllAsync();
53 | if (customers != null && customers.Count() > 0)
54 | {
55 | return Ok(customers);
56 | }
57 | return NoContent();
58 | }
59 |
60 | ///
61 | /// Get customer by id.
62 | ///
63 | // GET api/customers
64 | [HttpGet("{id}")]
65 | [ProducesResponseType(200)]
66 | [ProducesResponseType(400)]
67 | [ProducesResponseType(404)]
68 | [ProducesResponseType(500)]
69 | public async Task GetById(Guid id)
70 | {
71 | _iLogger.LogInformation($"Controller : {this.GetControllerName()} , Action {this.GetActionName()} : => Visited at {DateTime.UtcNow.ToLongTimeString()}");
72 |
73 | var customer = await _iCustomerService.GetByIdAsync(id);
74 | if (customer == null)
75 | {
76 | _iLogger.LogInformation($"Customer with {id} wasn't found");
77 | return NotFound();
78 | }
79 | return Ok(customer);
80 | }
81 |
82 | ///
83 | /// Add a new customer.
84 | ///
85 | // POST api/customers
86 | [HttpPost]
87 | [ValidateModelSate]
88 | [ProducesResponseType(201)]
89 | [ProducesResponseType(400)]
90 | [ProducesResponseType(409)]
91 | [ProducesResponseType(500)]
92 | public async Task Post([FromBody]CustomerModel customerModel)
93 | {
94 | _iLogger.LogInformation($"Controller : {this.GetControllerName()} , Action {this.GetActionName()} : => Visited at {DateTime.UtcNow.ToLongTimeString()}");
95 |
96 | var createdCustomer = await _iCustomerService.AddAsync(customerModel);
97 |
98 | return CreatedAtAction(nameof(GetById), new { id = createdCustomer.Id }, createdCustomer.Id);
99 | }
100 |
101 | ///
102 | /// Put a customer.
103 | ///
104 | // PUT api/customers/386a8d02-c13a-4f98-8edd-27ece9ee0472
105 | [HttpPut("{id}")]
106 | [ValidateModelSate]
107 | [ProducesResponseType(204)]
108 | [ProducesResponseType(400)]
109 | [ProducesResponseType(404)]
110 | [ProducesResponseType(500)]
111 | public async Task Put(Guid id, [FromBody]CustomerModel customerModel)
112 | {
113 | _iLogger.LogInformation($"Controller : {this.GetControllerName()} , Action {this.GetActionName()} : => Visited at {DateTime.UtcNow.ToLongTimeString()}");
114 |
115 | if (!(await CustomerExists(id)))
116 | {
117 | return NotFound();
118 | }
119 |
120 | _iCustomerService.Update(customerModel);
121 |
122 | return NoContent();
123 | }
124 |
125 | ///
126 | /// Delete customer by id.
127 | ///
128 | // DELETE api/customers/386a8d02-c13a-4f98-8edd-27ece9ee0472
129 | [HttpDelete("{id}")]
130 | [ProducesResponseType(204)]
131 | [ProducesResponseType(400)]
132 | [ProducesResponseType(404)]
133 | [ProducesResponseType(500)]
134 | public async Task Delete(Guid id)
135 | {
136 | _iLogger.LogInformation($"Controller : {this.GetControllerName()} , Action {this.GetActionName()} : => Visited at {DateTime.UtcNow.ToLongTimeString()}");
137 |
138 | if (!(await CustomerExists(id)))
139 | {
140 | return NotFound();
141 | }
142 |
143 | _iCustomerService.DeleteById(id);
144 |
145 | return NoContent();
146 | }
147 |
148 | private async Task CustomerExists(Guid id)
149 | {
150 | return (await _iCustomerService.GetAllAsync()).Any(a => a.Id.Equals(id));
151 | }
152 | #endregion
153 |
154 | #region GLOBAL
155 | #endregion
156 |
157 | #endregion
158 | }
159 | }
160 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Resources/AppResources.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 | text/microsoft-resx
110 |
111 |
112 | 2.0
113 |
114 |
115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
116 |
117 |
118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
119 |
120 |
121 | A problem happened while handling your request
122 |
123 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Resources/AppResources.en-US.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 | text/microsoft-resx
110 |
111 |
112 | 2.0
113 |
114 |
115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
116 |
117 |
118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
119 |
120 |
121 | A problem happened while handling your request
122 |
123 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Resources/AppResources.fr-FR.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 | text/microsoft-resx
110 |
111 |
112 | 2.0
113 |
114 |
115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
116 |
117 |
118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
119 |
120 |
121 | Un problème est survenu lors du traitement de votre demande
122 |
123 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 16
4 | VisualStudioVersion = 16.0.29509.3
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ASPNetCore.CleanArchitecture.Api", "ASPNetCore.CleanArchitecture\ASPNetCore.CleanArchitecture.Api\ASPNetCore.CleanArchitecture.Api.csproj", "{2CFBAA43-55A5-4C95-86D6-675B7B3BA8CE}"
7 | EndProject
8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ASPNetCore.CleanArchitecture.Data", "ASPNetCore.CleanArchitecture\ASPNetCore.CleanArchitecture.Data\ASPNetCore.CleanArchitecture.Data.csproj", "{FCB037C3-6B4D-42DC-9A6E-5282636C74C1}"
9 | EndProject
10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ASPNetCore.CleanArchitecture.Domain", "ASPNetCore.CleanArchitecture\ASPNetCore.CleanArchitecture.Domain\ASPNetCore.CleanArchitecture.Domain.csproj", "{DABFE91B-DBBB-45A6-A96D-3537F2F3E396}"
11 | EndProject
12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ASPNetCore.CleanArchitecture.Infrastructure", "ASPNetCore.CleanArchitecture\ASPNetCore.CleanArchitecture.Infrastructure\ASPNetCore.CleanArchitecture.Infrastructure.csproj", "{2608B6F4-177B-47E4-83E7-70BDCD1C39C1}"
13 | EndProject
14 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ASPNetCore.CleanArchitecture.Interfaces", "ASPNetCore.CleanArchitecture\ASPNetCore.CleanArchitecture.Interfaces\ASPNetCore.CleanArchitecture.Interfaces.csproj", "{29E413B8-9F03-4E77-91E9-412BB6E96FBB}"
15 | EndProject
16 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ASPNetCore.CleanArchitecture.Models", "ASPNetCore.CleanArchitecture\ASPNetCore.CleanArchitecture.Models\ASPNetCore.CleanArchitecture.Models.csproj", "{7C3A1950-C8AD-47D2-AE68-183979DA0B94}"
17 | EndProject
18 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ASPNetCore.CleanArchitecture.Setup", "ASPNetCore.CleanArchitecture\ASPNetCore.CleanArchitecture.Setup\ASPNetCore.CleanArchitecture.Setup.csproj", "{E35B12F7-4C6F-4F3D-B319-C5D9CC58A628}"
19 | EndProject
20 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ASPNetCore.CleanArchitecture.Resources", "ASPNetCore.CleanArchitecture\ASPNetCore.CleanArchitecture.Resources\ASPNetCore.CleanArchitecture.Resources.csproj", "{58BF689C-5482-4917-969B-3FE8FA4A9EA4}"
21 | EndProject
22 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ASPNetCore.CleanArchitecture.Patterns", "ASPNetCore.CleanArchitecture\ASPNetCore.CleanArchitecture.Patterns\ASPNetCore.CleanArchitecture.Patterns.csproj", "{C5426784-2EED-4F98-92C3-10B5753A843A}"
23 | EndProject
24 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ASPNetCore.CleanArchitecture.Exceptions", "ASPNetCore.CleanArchitecture\ASPNetCore.CleanArchitecture.Exceptions\ASPNetCore.CleanArchitecture.Exceptions.csproj", "{7D8DA1D0-85B8-4DB8-9025-881BCD8ECBC2}"
25 | EndProject
26 | Global
27 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
28 | Debug|Any CPU = Debug|Any CPU
29 | Release|Any CPU = Release|Any CPU
30 | EndGlobalSection
31 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
32 | {2CFBAA43-55A5-4C95-86D6-675B7B3BA8CE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
33 | {2CFBAA43-55A5-4C95-86D6-675B7B3BA8CE}.Debug|Any CPU.Build.0 = Debug|Any CPU
34 | {2CFBAA43-55A5-4C95-86D6-675B7B3BA8CE}.Release|Any CPU.ActiveCfg = Release|Any CPU
35 | {2CFBAA43-55A5-4C95-86D6-675B7B3BA8CE}.Release|Any CPU.Build.0 = Release|Any CPU
36 | {FCB037C3-6B4D-42DC-9A6E-5282636C74C1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
37 | {FCB037C3-6B4D-42DC-9A6E-5282636C74C1}.Debug|Any CPU.Build.0 = Debug|Any CPU
38 | {FCB037C3-6B4D-42DC-9A6E-5282636C74C1}.Release|Any CPU.ActiveCfg = Release|Any CPU
39 | {FCB037C3-6B4D-42DC-9A6E-5282636C74C1}.Release|Any CPU.Build.0 = Release|Any CPU
40 | {DABFE91B-DBBB-45A6-A96D-3537F2F3E396}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
41 | {DABFE91B-DBBB-45A6-A96D-3537F2F3E396}.Debug|Any CPU.Build.0 = Debug|Any CPU
42 | {DABFE91B-DBBB-45A6-A96D-3537F2F3E396}.Release|Any CPU.ActiveCfg = Release|Any CPU
43 | {DABFE91B-DBBB-45A6-A96D-3537F2F3E396}.Release|Any CPU.Build.0 = Release|Any CPU
44 | {2608B6F4-177B-47E4-83E7-70BDCD1C39C1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
45 | {2608B6F4-177B-47E4-83E7-70BDCD1C39C1}.Debug|Any CPU.Build.0 = Debug|Any CPU
46 | {2608B6F4-177B-47E4-83E7-70BDCD1C39C1}.Release|Any CPU.ActiveCfg = Release|Any CPU
47 | {2608B6F4-177B-47E4-83E7-70BDCD1C39C1}.Release|Any CPU.Build.0 = Release|Any CPU
48 | {29E413B8-9F03-4E77-91E9-412BB6E96FBB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
49 | {29E413B8-9F03-4E77-91E9-412BB6E96FBB}.Debug|Any CPU.Build.0 = Debug|Any CPU
50 | {29E413B8-9F03-4E77-91E9-412BB6E96FBB}.Release|Any CPU.ActiveCfg = Release|Any CPU
51 | {29E413B8-9F03-4E77-91E9-412BB6E96FBB}.Release|Any CPU.Build.0 = Release|Any CPU
52 | {7C3A1950-C8AD-47D2-AE68-183979DA0B94}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
53 | {7C3A1950-C8AD-47D2-AE68-183979DA0B94}.Debug|Any CPU.Build.0 = Debug|Any CPU
54 | {7C3A1950-C8AD-47D2-AE68-183979DA0B94}.Release|Any CPU.ActiveCfg = Release|Any CPU
55 | {7C3A1950-C8AD-47D2-AE68-183979DA0B94}.Release|Any CPU.Build.0 = Release|Any CPU
56 | {E35B12F7-4C6F-4F3D-B319-C5D9CC58A628}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
57 | {E35B12F7-4C6F-4F3D-B319-C5D9CC58A628}.Debug|Any CPU.Build.0 = Debug|Any CPU
58 | {E35B12F7-4C6F-4F3D-B319-C5D9CC58A628}.Release|Any CPU.ActiveCfg = Release|Any CPU
59 | {E35B12F7-4C6F-4F3D-B319-C5D9CC58A628}.Release|Any CPU.Build.0 = Release|Any CPU
60 | {58BF689C-5482-4917-969B-3FE8FA4A9EA4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
61 | {58BF689C-5482-4917-969B-3FE8FA4A9EA4}.Debug|Any CPU.Build.0 = Debug|Any CPU
62 | {58BF689C-5482-4917-969B-3FE8FA4A9EA4}.Release|Any CPU.ActiveCfg = Release|Any CPU
63 | {58BF689C-5482-4917-969B-3FE8FA4A9EA4}.Release|Any CPU.Build.0 = Release|Any CPU
64 | {C5426784-2EED-4F98-92C3-10B5753A843A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
65 | {C5426784-2EED-4F98-92C3-10B5753A843A}.Debug|Any CPU.Build.0 = Debug|Any CPU
66 | {C5426784-2EED-4F98-92C3-10B5753A843A}.Release|Any CPU.ActiveCfg = Release|Any CPU
67 | {C5426784-2EED-4F98-92C3-10B5753A843A}.Release|Any CPU.Build.0 = Release|Any CPU
68 | {7D8DA1D0-85B8-4DB8-9025-881BCD8ECBC2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
69 | {7D8DA1D0-85B8-4DB8-9025-881BCD8ECBC2}.Debug|Any CPU.Build.0 = Debug|Any CPU
70 | {7D8DA1D0-85B8-4DB8-9025-881BCD8ECBC2}.Release|Any CPU.ActiveCfg = Release|Any CPU
71 | {7D8DA1D0-85B8-4DB8-9025-881BCD8ECBC2}.Release|Any CPU.Build.0 = Release|Any CPU
72 | EndGlobalSection
73 | GlobalSection(SolutionProperties) = preSolution
74 | HideSolutionNode = FALSE
75 | EndGlobalSection
76 | GlobalSection(ExtensibilityGlobals) = postSolution
77 | SolutionGuid = {595BFF22-17BB-487E-838F-CEEC22E149C6}
78 | EndGlobalSection
79 | EndGlobal
80 |
--------------------------------------------------------------------------------
/ASPNetCore.CleanArchitecture/ASPNetCore.CleanArchitecture.Api/Controllers/ProductsController.cs:
--------------------------------------------------------------------------------
1 | /// Mohamed Ali NOUIRA
2 | /// http://www.mohamedalinouira.com
3 | /// https://github.com/medalinouira
4 | /// Copyright © Mohamed Ali NOUIRA. All rights reserved.
5 |
6 | using System;
7 | using ASPNetCore.CleanArchitecture.Models;
8 | using System.Linq;
9 | using ASPNetCore.CleanArchitecture.Api.Filters;
10 | using ASPNetCore.CleanArchitecture.Api.Extensions;
11 | using ASPNetCore.CleanArchitecture.Interfaces.IServices;
12 | using System.Threading.Tasks;
13 | using Microsoft.AspNetCore.Mvc;
14 | using Microsoft.Extensions.Logging;
15 | using ASPNetCore.CleanArchitecture.Api.Controllers.QueriesParams;
16 |
17 | namespace ASPNetCore.CleanArchitecture.Api.Controllers
18 | {
19 | [ApiVersion("2.0")]
20 | [ApiVersion("3.0")]
21 | [Route("api/v{version:apiVersion}/[controller]")]
22 | public class ProductsController : Controller
23 | {
24 | #region Fields
25 | private readonly IProductService _iProductService;
26 | private readonly ILogger _iLogger;
27 | #endregion
28 |
29 | #region Constructor
30 | public ProductsController(IProductService _iProductService,
31 | ILogger _iLogger)
32 | {
33 | this._iLogger = _iLogger;
34 | this._iProductService = _iProductService;
35 | }
36 | #endregion
37 |
38 | #region Actions
39 |
40 | #region CRUD
41 | ///
42 | /// Get all products.
43 | ///
44 | // GET: api/products
45 | [HttpGet]
46 | [ProducesResponseType(200)]
47 | [ProducesResponseType(204)]
48 | [ProducesResponseType(500)]
49 | public async Task GetAll()
50 | {
51 | _iLogger.LogInformation($"Controller : {this.GetControllerName()} , Action {this.GetActionName()} : => Visited at {DateTime.UtcNow.ToLongTimeString()}");
52 |
53 | var products = await _iProductService.GetAllAsync();
54 | if (products != null && products.Count() > 0)
55 | {
56 | return Ok(products);
57 | }
58 | return NoContent();
59 | }
60 |
61 | ///
62 | /// Get product by id.
63 | ///
64 | // GET api/products
65 | [HttpGet("{id}")]
66 | [ProducesResponseType(200)]
67 | [ProducesResponseType(400)]
68 | [ProducesResponseType(404)]
69 | [ProducesResponseType(500)]
70 | public async Task GetById(Guid id)
71 | {
72 | _iLogger.LogInformation($"Controller : {this.GetControllerName()} , Action {this.GetActionName()} : => Visited at {DateTime.UtcNow.ToLongTimeString()}");
73 |
74 | var product = await _iProductService.GetByIdAsync(id);
75 | if (product == null)
76 | {
77 | _iLogger.LogInformation($"Product with {id} wasn't found");
78 | return NotFound();
79 | }
80 | return Ok(product);
81 | }
82 |
83 | ///
84 | /// Add a new product.
85 | ///
86 | // POST api/products
87 | [HttpPost]
88 | [ValidateModelSate]
89 | [ProducesResponseType(201)]
90 | [ProducesResponseType(400)]
91 | [ProducesResponseType(409)]
92 | [ProducesResponseType(500)]
93 | public async Task Post([FromBody]ProductModel productModel)
94 | {
95 | _iLogger.LogInformation($"Controller : {this.GetControllerName()} , Action {this.GetActionName()} : => Visited at {DateTime.UtcNow.ToLongTimeString()}");
96 |
97 | var createdProduct = await _iProductService.AddAsync(productModel);
98 |
99 | return CreatedAtAction(nameof(GetById), new { id = createdProduct.Id }, createdProduct.Id);
100 | }
101 |
102 | ///
103 | /// Put a product.
104 | ///
105 | // PUT api/products/386a8d02-c13a-4f98-8edd-27ece9ee0472
106 | [HttpPut("{id}")]
107 | [ValidateModelSate]
108 | [ProducesResponseType(204)]
109 | [ProducesResponseType(400)]
110 | [ProducesResponseType(404)]
111 | [ProducesResponseType(500)]
112 | public async Task Put(Guid id, [FromBody]ProductModel productModel)
113 | {
114 | _iLogger.LogInformation($"Controller : {this.GetControllerName()} , Action {this.GetActionName()} : => Visited at {DateTime.UtcNow.ToLongTimeString()}");
115 |
116 | if (!(await ProductExists(id)))
117 | {
118 | return NotFound();
119 | };
120 |
121 | _iProductService.Update(productModel);
122 |
123 | return NoContent();
124 | }
125 |
126 | ///
127 | /// Delete product by id.
128 | ///
129 | // DELETE api/products/386a8d02-c13a-4f98-8edd-27ece9ee0472
130 | [HttpDelete("{id}")]
131 | [ProducesResponseType(204)]
132 | [ProducesResponseType(400)]
133 | [ProducesResponseType(404)]
134 | [ProducesResponseType(500)]
135 | public async Task Delete(Guid id)
136 | {
137 | _iLogger.LogInformation($"Controller : {this.GetControllerName()} , Action {this.GetActionName()} : => Visited at {DateTime.UtcNow.ToLongTimeString()}");
138 |
139 | if (!(await ProductExists(id)))
140 | {
141 | return NotFound();
142 | }
143 |
144 | _iProductService.DeleteById(id);
145 |
146 | return NoContent();
147 | }
148 |
149 | private async Task ProductExists(Guid id)
150 | {
151 | return (await _iProductService.GetAllAsync()).Any(a => a.Id.Equals(id));
152 | }
153 | #endregion
154 |
155 | #region GLOBAL
156 | ///
157 | /// Get all products by filter.
158 | ///
159 | // GET: api/products/filter?Page=5&PageSize=10&Term=hey&SearchBy=Name&SortBy=Name&SortOrder=Ascending
160 | [HttpGet("filter")]
161 | [MapToApiVersion("3.0")]
162 | [ProducesResponseType(200)]
163 | [ProducesResponseType(204)]
164 | [ProducesResponseType(400)]
165 | [ProducesResponseType(500)]
166 | public IActionResult GetByFilter(IProductQueryParams _iProductQueryParams)
167 | {
168 | _iLogger.LogInformation($"Controller : {this.GetControllerName()} , Action {this.GetActionName()} : => Visited at {DateTime.UtcNow.ToLongTimeString()}");
169 |
170 | return NoContent();
171 | }
172 | #endregion
173 |
174 | #endregion
175 | }
176 | }
177 |
--------------------------------------------------------------------------------