├── UnitOfWorkDemo ├── EasyUowApplication │ ├── Startup.cs │ ├── appsettings.Development.json │ ├── appsettings.json │ ├── UowMiCakeModule.cs │ ├── WeatherForecast.cs │ ├── Repositories │ │ └── ItineraryRepository.cs │ ├── EasyUowApplication.csproj │ ├── Program.cs │ ├── EFCore │ │ └── UowAppDbContext.cs │ ├── Middleware │ │ └── UnitOfWorkMiddleware.cs │ ├── Aggregates │ │ └── Itinerary.cs │ ├── Migrations │ │ ├── 20191224095055_InitialCreate.cs │ │ ├── UowAppDbContextModelSnapshot.cs │ │ └── 20191224095055_InitialCreate.Designer.cs │ └── Controllers │ │ └── WeatherForecastController.cs ├── MiCake.Uow.Easy │ ├── IUnitOfWokrProvider.cs │ ├── MiCake.Uow.Easy.csproj │ ├── ITransactionFeatureContainer.cs │ ├── MiCakeUowEasyModule.cs │ ├── IUnitOfWorkManager.cs │ ├── UnitOfWorkOptions.cs │ ├── IUnitOfWork.cs │ ├── ITransactionFeature.cs │ ├── UnitOfWorkManager.cs │ └── UnitOfWork.cs ├── MiCake.EFCore.Easy │ ├── IUowDbContextFactory.cs │ ├── MiCake.EFCore.Easy.csproj │ ├── Extension │ │ ├── MiCakeAspnetApplicationBuilderExtension.cs │ │ └── MiCakeAspNetSericesExtension.cs │ ├── EFRepository.cs │ ├── UowDbContextFactory.cs │ └── EFTranscationFeature.cs ├── README.md └── MiCake.Uow.Easy.sln ├── DomianEventDemo ├── DomainEventDemo │ ├── IDomainEvent.cs │ ├── IDomianEventProvider.cs │ ├── IDomainEventHandler.cs │ ├── DomainEventDemo.csproj │ ├── EventDispatch │ │ ├── IEventDispatcher.cs │ │ ├── DomainEventHandlerWrapper.cs │ │ └── EventDispatcher.cs │ ├── IEntity.cs │ ├── EntityHelper.cs │ ├── Entity.cs │ └── Registrar │ │ └── DomainEventHandlerRegistrar.cs ├── ConsoleApp1 │ ├── ConsoleApp1.csproj │ ├── Domain │ │ └── OneBoundContext │ │ │ ├── DomainEvents │ │ │ └── ProductAddedEvent.cs │ │ │ ├── Aggregates │ │ │ ├── RecommendProduct.cs │ │ │ └── ShoppingCart.cs │ │ │ └── DomainEventHandlers │ │ │ └── ProductAddedEventHandler.cs │ └── Program.cs └── DomianEventDemo.sln ├── README.md ├── LICENSE └── .gitignore /UnitOfWorkDemo/EasyUowApplication/Startup.cs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uoyoCsharp/HowToDDD/HEAD/UnitOfWorkDemo/EasyUowApplication/Startup.cs -------------------------------------------------------------------------------- /DomianEventDemo/DomainEventDemo/IDomainEvent.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace DomainEventDemo 6 | { 7 | public interface IDomainEvent 8 | { 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /UnitOfWorkDemo/EasyUowApplication/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Debug", 5 | "System": "Information", 6 | "Microsoft": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /UnitOfWorkDemo/EasyUowApplication/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "AllowedHosts": "*" 10 | } 11 | -------------------------------------------------------------------------------- /UnitOfWorkDemo/EasyUowApplication/UowMiCakeModule.cs: -------------------------------------------------------------------------------- 1 | using MiCake.Core.Abstractions.Modularity; 2 | using MiCake.Uow.Easy; 3 | 4 | namespace EasyUowApplication 5 | { 6 | [DependOn(typeof(MiCakeUowEasyModule))] 7 | public class UowMiCakeModule : MiCakeModule 8 | { 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /UnitOfWorkDemo/MiCake.Uow.Easy/IUnitOfWokrProvider.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace MiCake.Uow.Easy 6 | { 7 | public interface IUnitOfWokrProvider 8 | { 9 | IUnitOfWork GetCurrentUnitOfWork(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /UnitOfWorkDemo/MiCake.EFCore.Easy/IUowDbContextFactory.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | 3 | namespace MiCake.EFCore.Easy 4 | { 5 | internal interface IUowDbContextFactory 6 | where TDbCotnext : DbContext 7 | { 8 | TDbCotnext CreateDbContext(); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /UnitOfWorkDemo/MiCake.Uow.Easy/MiCake.Uow.Easy.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /DomianEventDemo/DomainEventDemo/IDomianEventProvider.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace DomainEventDemo 4 | { 5 | public interface IDomainEventProvider 6 | { 7 | /// 8 | /// Get All DomainEvents 9 | /// 10 | List GetDomainEvents(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /DomianEventDemo/ConsoleApp1/ConsoleApp1.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | netcoreapp3.1 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /DomianEventDemo/DomainEventDemo/IDomainEventHandler.cs: -------------------------------------------------------------------------------- 1 | using System.Threading; 2 | using System.Threading.Tasks; 3 | 4 | namespace DomainEventDemo 5 | { 6 | public interface IDomainEventHandler 7 | where TDomainEvent : IDomainEvent 8 | { 9 | Task HandleAysnc(TDomainEvent domainEvent, CancellationToken cancellationToken = default); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /UnitOfWorkDemo/EasyUowApplication/WeatherForecast.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace EasyUowApplication 4 | { 5 | public class WeatherForecast 6 | { 7 | public DateTime Date { get; set; } 8 | 9 | public int TemperatureC { get; set; } 10 | 11 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); 12 | 13 | public string Summary { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # HowToDDD 2 | 3 | 《如何运用领域驱动设计》 文章中的附录代码: 4 | 5 | + `DomianEventDemo` 文件夹下对应了[《如何运用领域驱动设计 - 领域事件》](https://www.cnblogs.com/uoyo/p/12421553.html)下的附件代码。 6 | + `UnitOfWorkDemo` 文件夹下对应了[《如何运用领域驱动设计 - 工作单元》](https://www.cnblogs.com/uoyo/p/12129344.html)下的附件代码。 7 | 8 | ## 备注 9 | 10 | 关于工作单元的版本: 您可以查看MiCake中关于工作单元的实现,它支持多种数据库源共用事务。 [【MiCake Github】](https://github.com/uoyoCsharp/MiCake/tree/master/src/framework/MiCake.Uow) 11 | -------------------------------------------------------------------------------- /DomianEventDemo/ConsoleApp1/Domain/OneBoundContext/DomainEvents/ProductAddedEvent.cs: -------------------------------------------------------------------------------- 1 | using DomainEventDemo; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace ConsoleApp1.Domain.OneBoundContext.DomainEvents 7 | { 8 | public class ProductAddedEvent:IDomainEvent 9 | { 10 | public Guid ProductID { get; set; } 11 | 12 | public string SomeInfo { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /DomianEventDemo/DomainEventDemo/DomainEventDemo.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /DomianEventDemo/DomainEventDemo/EventDispatch/IEventDispatcher.cs: -------------------------------------------------------------------------------- 1 | using System.Threading; 2 | using System.Threading.Tasks; 3 | 4 | namespace DomainEventDemo.EventDispatch 5 | { 6 | public interface IEventDispatcher 7 | { 8 | void Dispatch(TDomainEvent domainEvent) where TDomainEvent : IDomainEvent; 9 | 10 | Task DispatchAsync(TDomainEvent domainEvent, CancellationToken cancellationToken = default) where TDomainEvent : IDomainEvent; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /DomianEventDemo/ConsoleApp1/Domain/OneBoundContext/Aggregates/RecommendProduct.cs: -------------------------------------------------------------------------------- 1 | using DomainEventDemo; 2 | using System; 3 | 4 | namespace ConsoleApp1.Domain.OneBoundContext.Aggregates 5 | { 6 | public class RecommendProduct : Entity 7 | { 8 | public RecommendProduct() 9 | { 10 | } 11 | 12 | public void UpdateRecommendProduct(Guid productID) 13 | { 14 | //do something 15 | 16 | Console.WriteLine($"根据ID :{productID},推荐一些奇奇怪怪的商品"); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /UnitOfWorkDemo/MiCake.Uow.Easy/ITransactionFeatureContainer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace MiCake.Uow.Easy 6 | { 7 | public interface ITransactionFeatureContainer 8 | { 9 | void RegisteTranasctionFeature(string key, ITransactionFeature TransactionFeature); 10 | 11 | ITransactionFeature GetOrAddTransactionFeature(string key, ITransactionFeature TransactionFeature); 12 | 13 | ITransactionFeature GetTransactionFeature(string key); 14 | 15 | void RemoveTransaction(string key); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /DomianEventDemo/DomainEventDemo/IEntity.cs: -------------------------------------------------------------------------------- 1 | namespace DomainEventDemo 2 | { 3 | public interface IEntity : IDomainEventProvider 4 | { 5 | void AddDomainEvent(IDomainEvent domainEvent); 6 | 7 | void RemoveDomainEvent(IDomainEvent domainEvent); 8 | } 9 | 10 | /// 11 | /// Defines an entity with a single primary key with "Id" property. 12 | /// 13 | public interface IEntity : IEntity 14 | { 15 | /// 16 | /// Unique identifier for this entity. 17 | /// 18 | TKey Id { get; set; } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /UnitOfWorkDemo/EasyUowApplication/Repositories/ItineraryRepository.cs: -------------------------------------------------------------------------------- 1 | using EasyUowApplication.Aggregates; 2 | using EasyUowApplication.EFCore; 3 | using MiCake.Uow.Easy; 4 | using System; 5 | using MiCake.EFCore.Easy; 6 | 7 | namespace EasyUowApplication.Repositories 8 | { 9 | public class ItineraryRepository : EFRepository 10 | { 11 | public ItineraryRepository(IUnitOfWorkManager uowManager) : base(uowManager) 12 | { 13 | } 14 | 15 | public void Add(Itinerary itinerary) 16 | { 17 | DbContext.Set().Add(itinerary); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /UnitOfWorkDemo/MiCake.Uow.Easy/MiCakeUowEasyModule.cs: -------------------------------------------------------------------------------- 1 | using MiCake.Core.Abstractions.Modularity; 2 | using Microsoft.Extensions.DependencyInjection; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Text; 6 | 7 | namespace MiCake.Uow.Easy 8 | { 9 | public class MiCakeUowEasyModule : MiCakeModule 10 | { 11 | public MiCakeUowEasyModule() 12 | { 13 | } 14 | 15 | 16 | //添加需要所需要的注入服务 17 | public override void ConfigServices(ModuleConfigServiceContext context) 18 | { 19 | context.Services.AddSingleton(); 20 | context.Services.AddTransient(); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /UnitOfWorkDemo/MiCake.EFCore.Easy/MiCake.EFCore.Easy.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /DomianEventDemo/ConsoleApp1/Domain/OneBoundContext/Aggregates/ShoppingCart.cs: -------------------------------------------------------------------------------- 1 | using ConsoleApp1.Domain.OneBoundContext.DomainEvents; 2 | using DomainEventDemo; 3 | using System; 4 | 5 | namespace ConsoleApp1.Domain.OneBoundContext.Aggregates 6 | { 7 | public class ShoppingCart : Entity 8 | { 9 | public ShoppingCart() 10 | { 11 | 12 | } 13 | 14 | //此处参数可能是一个Product实体,但是为了简单此处只用了ID 15 | public void AddProductToCart(Guid productID, string ProductInfo) 16 | { 17 | // doing something. 18 | 19 | Console.WriteLine("商品已经被添加到了购物车"); 20 | 21 | this.AddDomainEvent(new ProductAddedEvent() { ProductID = productID, SomeInfo = ProductInfo }); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /UnitOfWorkDemo/MiCake.Uow.Easy/IUnitOfWorkManager.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace MiCake.Uow.Easy 6 | { 7 | /// 8 | /// 工作单元管理类,用于维护和创建工作单元 9 | /// 10 | public interface IUnitOfWorkManager : IUnitOfWokrProvider, IDisposable 11 | { 12 | /// 13 | /// Create a with a default options 14 | /// 15 | IUnitOfWork Create(); 16 | 17 | /// 18 | /// Create a with a custom options 19 | /// 20 | /// 21 | /// 22 | IUnitOfWork Create(UnitOfWorkOptions options); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /UnitOfWorkDemo/EasyUowApplication/EasyUowApplication.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.0 5 | 6 | 7 | 8 | 9 | all 10 | runtime; build; native; contentfiles; analyzers; buildtransitive 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /UnitOfWorkDemo/MiCake.EFCore.Easy/Extension/MiCakeAspnetApplicationBuilderExtension.cs: -------------------------------------------------------------------------------- 1 | using MiCake.Core.Abstractions; 2 | using Microsoft.AspNetCore.Builder; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Text; 6 | using Microsoft.Extensions.DependencyInjection; 7 | 8 | namespace MiCake.EFCore.Easy.Extension 9 | { 10 | public static class MiCakeAspnetApplicationBuilderExtension 11 | { 12 | public static IApplicationBuilder InitMiCake(this IApplicationBuilder app) 13 | { 14 | var provider = app.ApplicationServices; 15 | var micakeApp = provider.GetRequiredService(typeof(IMiCakeApplicationProvider)); 16 | ((IMiCakeApplicationProvider)micakeApp)?.Initialize(provider); 17 | 18 | return app; 19 | } 20 | 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /UnitOfWorkDemo/EasyUowApplication/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Hosting; 6 | using Microsoft.Extensions.Configuration; 7 | using Microsoft.Extensions.Hosting; 8 | using Microsoft.Extensions.Logging; 9 | 10 | namespace EasyUowApplication 11 | { 12 | public class Program 13 | { 14 | public static void Main(string[] args) 15 | { 16 | CreateHostBuilder(args).Build().Run(); 17 | } 18 | 19 | public static IHostBuilder CreateHostBuilder(string[] args) => 20 | Host.CreateDefaultBuilder(args) 21 | .ConfigureWebHostDefaults(webBuilder => 22 | { 23 | webBuilder.UseStartup(); 24 | }); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /UnitOfWorkDemo/MiCake.EFCore.Easy/Extension/MiCakeAspNetSericesExtension.cs: -------------------------------------------------------------------------------- 1 | using MiCake.Core; 2 | using MiCake.Core.Abstractions; 3 | using MiCake.Core.Abstractions.Builder; 4 | using Microsoft.Extensions.DependencyInjection; 5 | using System; 6 | 7 | namespace MiCake.EFCore.Easy.Extension 8 | { 9 | public static class MiCakeAspNetSericesExtension 10 | { 11 | public static IMiCakeApplication AddMiCake(this IServiceCollection services) 12 | { 13 | return MiCakeApplictionFactory.Create(services); 14 | } 15 | 16 | public static IMiCakeApplication AddMiCake(this IServiceCollection services, Action builderConfigAction) 17 | { 18 | return MiCakeApplictionFactory.Create(services, builderConfigAction); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /UnitOfWorkDemo/EasyUowApplication/EFCore/UowAppDbContext.cs: -------------------------------------------------------------------------------- 1 | using EasyUowApplication.Aggregates; 2 | using Microsoft.EntityFrameworkCore; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Threading.Tasks; 7 | 8 | namespace EasyUowApplication.EFCore 9 | { 10 | public class UowAppDbContext : DbContext 11 | { 12 | public UowAppDbContext(DbContextOptions options) : base(options) 13 | { 14 | } 15 | 16 | public DbSet Itinerarys { get; set; } 17 | 18 | protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) 19 | { 20 | //optionsBuilder.UseMySql("Server=localhost;Database=uowexample;User=root;Password=a12345;", mySqlOptions => mySqlOptions 21 | // .ServerVersion(new ServerVersion(new Version(10, 5, 0), ServerType.MariaDb))); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /UnitOfWorkDemo/EasyUowApplication/Middleware/UnitOfWorkMiddleware.cs: -------------------------------------------------------------------------------- 1 | using MiCake.Uow.Easy; 2 | using Microsoft.AspNetCore.Http; 3 | using System.Threading.Tasks; 4 | 5 | namespace EasyUowApplication.Middleware 6 | { 7 | public class UnitOfWorkMiddleware 8 | { 9 | private readonly RequestDelegate _next; 10 | private readonly IUnitOfWorkManager _unitOfWorkManager; 11 | 12 | public UnitOfWorkMiddleware(RequestDelegate next, IUnitOfWorkManager unitOfWorkManager) 13 | { 14 | _next = next; 15 | _unitOfWorkManager = unitOfWorkManager; 16 | } 17 | 18 | public async Task Invoke(HttpContext httpContext) 19 | { 20 | using (var uow = _unitOfWorkManager.Create()) 21 | { 22 | await _next(httpContext); 23 | await uow.SaveChangesAsync(); 24 | } 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /UnitOfWorkDemo/MiCake.Uow.Easy/UnitOfWorkOptions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Data; 4 | using System.Text; 5 | 6 | namespace MiCake.Uow.Easy 7 | { 8 | public class UnitOfWorkOptions 9 | { 10 | public IsolationLevel? IsolationLevel { get; set; } 11 | 12 | public TimeSpan? Timeout { get; set; } 13 | 14 | public UnitOfWorkOptions() : this(default) 15 | { 16 | } 17 | 18 | public UnitOfWorkOptions(IsolationLevel? isolationLevel) : 19 | this(isolationLevel, null) 20 | { 21 | } 22 | 23 | public UnitOfWorkOptions(IsolationLevel? isolationLevel, TimeSpan? timeOut) 24 | { 25 | IsolationLevel = isolationLevel; 26 | Timeout = timeOut; 27 | } 28 | 29 | public UnitOfWorkOptions Clone() 30 | { 31 | return new UnitOfWorkOptions(IsolationLevel, Timeout); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /DomianEventDemo/ConsoleApp1/Domain/OneBoundContext/DomainEventHandlers/ProductAddedEventHandler.cs: -------------------------------------------------------------------------------- 1 | using ConsoleApp1.Domain.OneBoundContext.Aggregates; 2 | using ConsoleApp1.Domain.OneBoundContext.DomainEvents; 3 | using DomainEventDemo; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Text; 7 | using System.Threading; 8 | using System.Threading.Tasks; 9 | 10 | namespace ConsoleApp1.Domain.OneBoundContext.DomainEventHandlers 11 | { 12 | class ProductAddedEventHandler : IDomainEventHandler 13 | { 14 | public Task HandleAysnc(ProductAddedEvent domainEvent, CancellationToken cancellationToken = default) 15 | { 16 | //do something....... 17 | 18 | //此处您可能通过仓储来获取 19 | var recommendProduct = new RecommendProduct(); 20 | 21 | recommendProduct.UpdateRecommendProduct(domainEvent.ProductID); 22 | 23 | return Task.CompletedTask; 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /UnitOfWorkDemo/EasyUowApplication/Aggregates/Itinerary.cs: -------------------------------------------------------------------------------- 1 | using MiCake.DDD.Domain; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | namespace EasyUowApplication.Aggregates 8 | { 9 | public class Itinerary : AggregateRoot 10 | { 11 | public string Participants { get; set; } 12 | 13 | public string Places { get; set; } 14 | 15 | public string Note { get; set; } 16 | 17 | public string TripTime { get; set; } 18 | 19 | public string Status { get; set; } 20 | 21 | public Itinerary() 22 | { 23 | Id = Guid.NewGuid(); 24 | } 25 | 26 | //ctor 27 | public Itinerary(string p1, string p2, string p3, string p4, string p5) 28 | { 29 | Id = Guid.NewGuid(); 30 | Participants = p1; 31 | Places = p2; 32 | Note = p3; 33 | TripTime = p4; 34 | Status = p5; 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 uoyo 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /UnitOfWorkDemo/MiCake.Uow.Easy/IUnitOfWork.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | 5 | namespace MiCake.Uow.Easy 6 | { 7 | public interface IUnitOfWork : IDisposable, ITransactionFeatureContainer 8 | { 9 | Guid ID { get; } 10 | 11 | bool IsDisposed { get; } 12 | 13 | UnitOfWorkOptions UnitOfWorkOptions { get; } 14 | 15 | /// 16 | /// a unit of work scoped serviceprovider. 17 | /// can get db instance or transaction instance in this scope. 18 | /// for example:in ef core.can get a dbcontext with uow scope. 19 | /// 20 | public IServiceProvider ServiceProvider { get; } 21 | 22 | void SetOptions(UnitOfWorkOptions options); 23 | 24 | void SaveChanges(); 25 | 26 | Task SaveChangesAsync(CancellationToken cancellationToken = default); 27 | 28 | void Rollback(); 29 | 30 | Task RollbackAsync(CancellationToken cancellationToken = default); 31 | 32 | event EventHandler DisposeHandler; 33 | 34 | void OnSaveChanged(Action action); 35 | void OnRollBacked(Action action); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /DomianEventDemo/ConsoleApp1/Program.cs: -------------------------------------------------------------------------------- 1 | using ConsoleApp1.Domain.OneBoundContext.Aggregates; 2 | using DomainEventDemo.EventDispatch; 3 | using DomainEventDemo.Registrar; 4 | using Microsoft.Extensions.DependencyInjection; 5 | using System; 6 | using System.Reflection; 7 | 8 | namespace ConsoleApp1 9 | { 10 | class Program 11 | { 12 | static void Main(string[] args) 13 | { 14 | IServiceCollection services = new ServiceCollection(); 15 | services.AddSingleton(); 16 | 17 | var needScanAsm = new Assembly[1] { typeof(Program).Assembly }; 18 | DomainEventHandlerRegistrar.ResigterDomainEventHandler(services, needScanAsm); 19 | 20 | var shoppingCart = new ShoppingCart(); 21 | 22 | //添加一些商品 23 | shoppingCart.AddProductToCart(Guid.NewGuid(), "no info"); 24 | 25 | //该处操作一般放置在工作单元保存之前,比如EF Core 的 savechanges 之前 26 | var dispatcher = services.BuildServiceProvider().GetService(); 27 | foreach (var @event in shoppingCart.GetDomainEvents()) 28 | { 29 | dispatcher.Dispatch(@event); 30 | } 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /DomianEventDemo/DomainEventDemo/EventDispatch/DomainEventHandlerWrapper.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | 8 | namespace DomainEventDemo.EventDispatch 9 | { 10 | internal abstract class DomainEventHandlerWrapper 11 | { 12 | public abstract Task Handle(IDomainEvent domainEvent, CancellationToken cancellationToken, IServiceProvider serviceProvider, Func>, Task> publish); 13 | } 14 | 15 | internal class DomainEventHandlerWrapperImp : DomainEventHandlerWrapper 16 | where TDomainEvent : IDomainEvent 17 | { 18 | public override Task Handle(IDomainEvent domainEvent, CancellationToken cancellationToken, IServiceProvider serviceProvider, Func>, Task> publish) 19 | { 20 | var handlers = serviceProvider 21 | .GetServices>() 22 | .Select(x => new Func(() => x.HandleAysnc((TDomainEvent)domainEvent, cancellationToken))); 23 | 24 | return publish(handlers); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /UnitOfWorkDemo/EasyUowApplication/Migrations/20191224095055_InitialCreate.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.EntityFrameworkCore.Migrations; 3 | 4 | namespace EasyUowApplication.Migrations 5 | { 6 | public partial class InitialCreate : Migration 7 | { 8 | protected override void Up(MigrationBuilder migrationBuilder) 9 | { 10 | migrationBuilder.CreateTable( 11 | name: "Itinerarys", 12 | columns: table => new 13 | { 14 | Id = table.Column(nullable: false), 15 | Participants = table.Column(nullable: true), 16 | Places = table.Column(nullable: true), 17 | Note = table.Column(nullable: true), 18 | TripTime = table.Column(nullable: true), 19 | Status = table.Column(nullable: true) 20 | }, 21 | constraints: table => 22 | { 23 | table.PrimaryKey("PK_Itinerarys", x => x.Id); 24 | }); 25 | } 26 | 27 | protected override void Down(MigrationBuilder migrationBuilder) 28 | { 29 | migrationBuilder.DropTable( 30 | name: "Itinerarys"); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /UnitOfWorkDemo/MiCake.Uow.Easy/ITransactionFeature.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | 5 | namespace MiCake.Uow.Easy 6 | { 7 | /// 8 | /// Mark a api has transcation funcation. 9 | /// 10 | public interface ITransactionFeature : IDisposable 11 | { 12 | public bool IsCommit { get; } 13 | 14 | public bool IsRollback { get; } 15 | 16 | /// 17 | /// Commits all changes made to the database in the current transaction. 18 | /// 19 | void Commit(); 20 | 21 | /// 22 | /// Commits all changes made to the database in the current transaction asynchronously. 23 | /// 24 | /// The cancellation token. 25 | Task CommitAsync(CancellationToken cancellationToken = default); 26 | 27 | /// 28 | /// Discards all changes made to the database in the current transaction. 29 | /// 30 | void Rollback(); 31 | 32 | /// 33 | /// Discards all changes made to the database in the current transaction asynchronously. 34 | /// 35 | /// The cancellation token. 36 | Task RollbackAsync(CancellationToken cancellationToken = default); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /UnitOfWorkDemo/MiCake.EFCore.Easy/EFRepository.cs: -------------------------------------------------------------------------------- 1 | using MiCake.DDD.Domain; 2 | using MiCake.Uow.Easy; 3 | using Microsoft.EntityFrameworkCore; 4 | using System; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | 8 | namespace MiCake.EFCore.Easy 9 | { 10 | public class EFRepository : IReadOnlyRepository 11 | where TAggregateRoot : class, IAggregateRoot 12 | where TDbContext : DbContext 13 | { 14 | public virtual TDbContext DbContext 15 | { 16 | get 17 | { 18 | return _dbContextFactory.CreateDbContext(); 19 | } 20 | } 21 | 22 | private readonly IUnitOfWorkManager _uowManager; 23 | private IUowDbContextFactory _dbContextFactory; 24 | 25 | public EFRepository(IUnitOfWorkManager uowManager) 26 | { 27 | _uowManager = uowManager; 28 | 29 | _dbContextFactory = new UowDbContextFactory(_uowManager); 30 | } 31 | 32 | public virtual TAggregateRoot Find(TKey ID) 33 | { 34 | return DbContext.Find(ID); 35 | } 36 | 37 | public virtual Task FindAsync(TKey ID, CancellationToken cancellationToken = default) 38 | { 39 | return DbContext.FindAsync(ID, cancellationToken).AsTask(); 40 | } 41 | 42 | public virtual long GetCount() 43 | { 44 | return DbContext.Set().LongCountAsync().Result; 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /DomianEventDemo/DomainEventDemo/EntityHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Reflection; 4 | 5 | namespace DomainEventDemo 6 | { 7 | public static class EntityHelper 8 | { 9 | public static bool IsEntity(Type type) 10 | { 11 | return typeof(IEntity).IsAssignableFrom(type); 12 | } 13 | 14 | public static bool HasDefaultId( IEntity entity) 15 | { 16 | if (EqualityComparer.Default.Equals(entity.Id, default)) 17 | { 18 | return true; 19 | } 20 | 21 | return false; 22 | } 23 | 24 | public static Type FindPrimaryKeyType() 25 | where TEntity : IEntity 26 | { 27 | return FindPrimaryKeyType(typeof(TEntity)); 28 | } 29 | 30 | public static Type FindPrimaryKeyType( Type entityType) 31 | { 32 | if (!typeof(IEntity).IsAssignableFrom(entityType)) 33 | { 34 | throw new ArgumentException($"Given {nameof(entityType)} is not an entity. It should implement {typeof(IEntity).AssemblyQualifiedName}!"); 35 | } 36 | 37 | foreach (var interfaceType in entityType.GetTypeInfo().GetInterfaces()) 38 | { 39 | if (interfaceType.GetTypeInfo().IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(IEntity<>)) 40 | { 41 | return interfaceType.GenericTypeArguments[0]; 42 | } 43 | } 44 | 45 | return null; 46 | } 47 | 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /UnitOfWorkDemo/EasyUowApplication/Controllers/WeatherForecastController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using EasyUowApplication.Aggregates; 5 | using EasyUowApplication.Repositories; 6 | using Microsoft.AspNetCore.Mvc; 7 | using Microsoft.Extensions.Logging; 8 | 9 | namespace EasyUowApplication.Controllers 10 | { 11 | [ApiController] 12 | [Route("[controller]")] 13 | public class WeatherForecastController : ControllerBase 14 | { 15 | private static readonly string[] Summaries = new[] 16 | { 17 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" 18 | }; 19 | 20 | private readonly ILogger _logger; 21 | private readonly ItineraryRepository _itineraryRepository; 22 | 23 | public WeatherForecastController(ILogger logger, ItineraryRepository itineraryRepository) 24 | { 25 | _logger = logger; 26 | _itineraryRepository = itineraryRepository; 27 | } 28 | 29 | [HttpPost] 30 | public ActionResult Add() 31 | { 32 | //使用仓储来处理聚合 33 | _itineraryRepository.Add(new Itinerary("奥特曼", "赛文奥特曼", "杰克奥特曼", "佐菲奥特曼", "泰罗奥特曼")); 34 | _itineraryRepository.Add(new Itinerary("盖亚奥特曼", "戴拿奥特曼", "阿古茹奥特曼", "迪迦奥特曼", "")); 35 | 36 | return "success"; 37 | } 38 | 39 | [HttpGet] 40 | public ActionResult Get() 41 | { 42 | var count = _itineraryRepository.GetCount(); 43 | return count; 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /DomianEventDemo/DomianEventDemo.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29709.97 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ConsoleApp1", "ConsoleApp1\ConsoleApp1.csproj", "{E353F68D-62C0-4930-BE32-C241831A90B4}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DomainEventDemo", "DomainEventDemo\DomainEventDemo.csproj", "{CE0EBA0A-5678-4C08-8FD0-2D420C241658}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {E353F68D-62C0-4930-BE32-C241831A90B4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {E353F68D-62C0-4930-BE32-C241831A90B4}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {E353F68D-62C0-4930-BE32-C241831A90B4}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {E353F68D-62C0-4930-BE32-C241831A90B4}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {CE0EBA0A-5678-4C08-8FD0-2D420C241658}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {CE0EBA0A-5678-4C08-8FD0-2D420C241658}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {CE0EBA0A-5678-4C08-8FD0-2D420C241658}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {CE0EBA0A-5678-4C08-8FD0-2D420C241658}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {669FD2EB-D5F6-4BC3-90D1-B7352F540399} 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /UnitOfWorkDemo/EasyUowApplication/Migrations/UowAppDbContextModelSnapshot.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using EasyUowApplication.EFCore; 4 | using Microsoft.EntityFrameworkCore; 5 | using Microsoft.EntityFrameworkCore.Infrastructure; 6 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 7 | 8 | namespace EasyUowApplication.Migrations 9 | { 10 | [DbContext(typeof(UowAppDbContext))] 11 | partial class UowAppDbContextModelSnapshot : ModelSnapshot 12 | { 13 | protected override void BuildModel(ModelBuilder modelBuilder) 14 | { 15 | #pragma warning disable 612, 618 16 | modelBuilder 17 | .HasAnnotation("ProductVersion", "3.1.0") 18 | .HasAnnotation("Relational:MaxIdentifierLength", 64); 19 | 20 | modelBuilder.Entity("EasyUowApplication.Aggregates.Itinerary", b => 21 | { 22 | b.Property("Id") 23 | .ValueGeneratedOnAdd() 24 | .HasColumnType("char(36)"); 25 | 26 | b.Property("Note") 27 | .HasColumnType("longtext CHARACTER SET utf8mb4"); 28 | 29 | b.Property("Participants") 30 | .HasColumnType("longtext CHARACTER SET utf8mb4"); 31 | 32 | b.Property("Places") 33 | .HasColumnType("longtext CHARACTER SET utf8mb4"); 34 | 35 | b.Property("Status") 36 | .HasColumnType("longtext CHARACTER SET utf8mb4"); 37 | 38 | b.Property("TripTime") 39 | .HasColumnType("longtext CHARACTER SET utf8mb4"); 40 | 41 | b.HasKey("Id"); 42 | 43 | b.ToTable("Itinerarys"); 44 | }); 45 | #pragma warning restore 612, 618 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /UnitOfWorkDemo/EasyUowApplication/Migrations/20191224095055_InitialCreate.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using EasyUowApplication.EFCore; 4 | using Microsoft.EntityFrameworkCore; 5 | using Microsoft.EntityFrameworkCore.Infrastructure; 6 | using Microsoft.EntityFrameworkCore.Migrations; 7 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 8 | 9 | namespace EasyUowApplication.Migrations 10 | { 11 | [DbContext(typeof(UowAppDbContext))] 12 | [Migration("20191224095055_InitialCreate")] 13 | partial class InitialCreate 14 | { 15 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 16 | { 17 | #pragma warning disable 612, 618 18 | modelBuilder 19 | .HasAnnotation("ProductVersion", "3.1.0") 20 | .HasAnnotation("Relational:MaxIdentifierLength", 64); 21 | 22 | modelBuilder.Entity("EasyUowApplication.Aggregates.Itinerary", b => 23 | { 24 | b.Property("Id") 25 | .ValueGeneratedOnAdd() 26 | .HasColumnType("char(36)"); 27 | 28 | b.Property("Note") 29 | .HasColumnType("longtext CHARACTER SET utf8mb4"); 30 | 31 | b.Property("Participants") 32 | .HasColumnType("longtext CHARACTER SET utf8mb4"); 33 | 34 | b.Property("Places") 35 | .HasColumnType("longtext CHARACTER SET utf8mb4"); 36 | 37 | b.Property("Status") 38 | .HasColumnType("longtext CHARACTER SET utf8mb4"); 39 | 40 | b.Property("TripTime") 41 | .HasColumnType("longtext CHARACTER SET utf8mb4"); 42 | 43 | b.HasKey("Id"); 44 | 45 | b.ToTable("Itinerarys"); 46 | }); 47 | #pragma warning restore 612, 618 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /UnitOfWorkDemo/README.md: -------------------------------------------------------------------------------- 1 | 2 | # MiCake.Uow.Easy 3 | 4 | ## 介绍 5 | 6 | 一个简单的工作单元实现。它是米蛋糕中工作单元的超简易版本,并不代表米蛋糕中真正的工作单元,该项目仅供参考使用。 7 | 8 | ## 构建步骤 9 | 10 | + 设置 **EasyUowApplication** 为项目启动项 11 | + 在Startup.cs中替换您的数据库链接字符串。并在数据库中创建对应数据库(案例中为mariadb中创建uowexample库)。 12 | 13 | ````c# 14 | //将数据库链接字符串替换为您的数据库 15 | services.AddDbContext(options => 16 | { 17 | options.UseMySql("Server=localhost;Database=uowexample;User=root;Password=a12345;", mySqlOptions => mySqlOptions 18 | .ServerVersion(new ServerVersion(new Version(10, 5, 0), ServerType.MariaDb))); 19 | }); 20 | ```` 21 | 22 | + 打开程序包管理控制台(ALT + T + N + O),执行EF 迁移命令 : **dotnet ef migrations add InitialCreate --project EasyUowApplication** 23 | + 继续执行Update语句: **dotnet ef database update --project EasyUowApplication** 24 | + OK,F5运行 25 | 26 | ## 项目配置项 27 | 28 | 本例子使用了 asp.net core 3.0 开发,所以在运行前请您确保您已经安装了新版的 Visual Studio 以及对应的.NET CORE SDK。 29 | 30 | 数据访问部分,使用了EF Core作为ORM框架,对应的数据库选取的是MariaDB(version:10.5.0),如果您愿意使用MariaDb作为测试数据库,请到MariaDb官网下载对应版本( [https://mariadb.org/](https://mariadb.org/) )。如果您愿意使用其他的数据库,比如Sqlserver,您可以修改EF Core中的数据库选择部分。 31 | 32 | 本例子引用了部分米蛋糕(MiCake)的nuget包,这些包目前还处于测试预览阶段,在此处使用仅仅是为了使用米蛋糕中的部分DDD特性接口。有关米蛋糕的后期介绍可以关注 [句幽的博客园](https://www.cnblogs.com/uoyo/) 。它是一个超轻柔的DDD组件,方便您的项目能够快速使用和进化为DDD模式,目前还处于开发阶段,后期测试完成后也将开源。 33 | 34 | ## 学习版本 35 | 36 | + 如果您是从 [如何运用领域驱动设计 - 存储库](https://www.cnblogs.com/uoyo/p/12097737.html) 文章跳转过来,请将GitHub的Tag标签选择为**repository**,该版本提供了超级简易的写法供您学习仓储和工作单元。 37 | 38 | ![branch](https://images.cnblogs.com/cnblogs_com/uoyo/1624074/o_191231032002QQ%E6%88%AA%E5%9B%BE20191231111913.png) 39 | 40 | + 其它情况下,您可以选择目前的master最新版本进行clone。 41 | 42 | ## 说明 43 | 44 | 本项目仅仅是《如何运用领域驱动设计》博文中的一个案例Demo,它借鉴了米蛋糕中工作单元的部分实现,并将其进行了极度的精简,为的只是让您更好的理解仓储和工作单元。有关《如何运用领域驱动设计》的文章,可以参考 [句幽的博客园](https://www.cnblogs.com/uoyo/) 。 45 | 46 | ## 问题 47 | 48 | 由于该项目仅仅是为了演示使用,虽然它实现了外界调用仓储时能自动完成事务,但是它依旧缺少了很多特性: 49 | 50 | + 一个业务操作(一个API)中没有创建多个工作单元的能力 51 | + 目前事务的操作来源于EF Core的支持,如果项目存在多种数据访问方式(比如一个EF,一个ADO),它们之间如何依靠工作单元来完成事务 52 | + 没有识别什么时候需要开启工作单元,如果一个操作仅仅需要获取数据,其实我们是不需要开启工作单元的 -------------------------------------------------------------------------------- /DomianEventDemo/DomainEventDemo/EventDispatch/EventDispatcher.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Collections.Generic; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | 7 | namespace DomainEventDemo.EventDispatch 8 | { 9 | public class EventDispatcher : IEventDispatcher 10 | { 11 | private static readonly ConcurrentDictionary _domainEventHandlers = new ConcurrentDictionary(); 12 | 13 | private IServiceProvider _serviceProvider; 14 | 15 | public EventDispatcher(IServiceProvider serviceProvider) 16 | { 17 | _serviceProvider = serviceProvider; 18 | } 19 | 20 | public void Dispatch(TDomainEvent domainEvent) 21 | where TDomainEvent : IDomainEvent 22 | { 23 | DispatchAsync(domainEvent).GetAwaiter().GetResult(); 24 | } 25 | 26 | public Task DispatchAsync(TDomainEvent domainEvent, CancellationToken cancellationToken = default) 27 | where TDomainEvent : IDomainEvent 28 | { 29 | if (domainEvent == null) 30 | return Task.CompletedTask; 31 | 32 | return PublishDomainEvents(domainEvent, cancellationToken); 33 | } 34 | 35 | protected virtual async Task PublishCore(IEnumerable> allHandlers) 36 | { 37 | foreach (var handler in allHandlers) 38 | { 39 | await handler().ConfigureAwait(false); 40 | } 41 | } 42 | 43 | private Task PublishDomainEvents(IDomainEvent domainEvent, CancellationToken cancellationToken = default) 44 | { 45 | var domainEventType = domainEvent.GetType(); 46 | var handler = _domainEventHandlers.GetOrAdd(domainEventType, 47 | factory => (DomainEventHandlerWrapper)Activator.CreateInstance(typeof(DomainEventHandlerWrapperImp<>).MakeGenericType(domainEventType))); 48 | 49 | return handler.Handle(domainEvent, cancellationToken, _serviceProvider, PublishCore); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /UnitOfWorkDemo/MiCake.Uow.Easy.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29613.14 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MiCake.Uow.Easy", "MiCake.Uow.Easy\MiCake.Uow.Easy.csproj", "{AA755A0A-C650-4BE4-B031-6E18C2E9B181}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MiCake.EFCore.Easy", "MiCake.EFCore.Easy\MiCake.EFCore.Easy.csproj", "{0AD9E73C-2561-43C7-910A-D208B9DC986A}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyUowApplication", "EasyUowApplication\EasyUowApplication.csproj", "{B0DFEB7A-94D3-4798-8864-BD6F827354AC}" 11 | EndProject 12 | Global 13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 14 | Debug|Any CPU = Debug|Any CPU 15 | Release|Any CPU = Release|Any CPU 16 | EndGlobalSection 17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 18 | {AA755A0A-C650-4BE4-B031-6E18C2E9B181}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 19 | {AA755A0A-C650-4BE4-B031-6E18C2E9B181}.Debug|Any CPU.Build.0 = Debug|Any CPU 20 | {AA755A0A-C650-4BE4-B031-6E18C2E9B181}.Release|Any CPU.ActiveCfg = Release|Any CPU 21 | {AA755A0A-C650-4BE4-B031-6E18C2E9B181}.Release|Any CPU.Build.0 = Release|Any CPU 22 | {0AD9E73C-2561-43C7-910A-D208B9DC986A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {0AD9E73C-2561-43C7-910A-D208B9DC986A}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {0AD9E73C-2561-43C7-910A-D208B9DC986A}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {0AD9E73C-2561-43C7-910A-D208B9DC986A}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {B0DFEB7A-94D3-4798-8864-BD6F827354AC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {B0DFEB7A-94D3-4798-8864-BD6F827354AC}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {B0DFEB7A-94D3-4798-8864-BD6F827354AC}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {B0DFEB7A-94D3-4798-8864-BD6F827354AC}.Release|Any CPU.Build.0 = Release|Any CPU 30 | EndGlobalSection 31 | GlobalSection(SolutionProperties) = preSolution 32 | HideSolutionNode = FALSE 33 | EndGlobalSection 34 | GlobalSection(ExtensibilityGlobals) = postSolution 35 | SolutionGuid = {C5431457-0FFF-4784-B346-8051600E578F} 36 | EndGlobalSection 37 | EndGlobal 38 | -------------------------------------------------------------------------------- /UnitOfWorkDemo/MiCake.EFCore.Easy/UowDbContextFactory.cs: -------------------------------------------------------------------------------- 1 | using MiCake.Uow.Easy; 2 | using Microsoft.EntityFrameworkCore; 3 | using System; 4 | 5 | namespace MiCake.EFCore.Easy 6 | { 7 | internal class UowDbContextFactory : IUowDbContextFactory 8 | where TDbContext : DbContext 9 | { 10 | private readonly IUnitOfWorkManager _uowManager; 11 | 12 | public UowDbContextFactory(IUnitOfWorkManager uowManager) 13 | { 14 | _uowManager = uowManager; 15 | } 16 | 17 | public TDbContext CreateDbContext() 18 | { 19 | var currentUow = _uowManager.GetCurrentUnitOfWork(); 20 | 21 | if (currentUow == null) 22 | throw new NullReferenceException("Cannot get a unit of work,Please check create root unit of work correctly"); 23 | 24 | var wantedDbContext = (TDbContext)currentUow.ServiceProvider.GetService(typeof(TDbContext)); 25 | 26 | if (wantedDbContext == null) 27 | throw new NullReferenceException("Cannot get DbContext.Please check add ef services correctly"); 28 | 29 | AddDbTransactionFeatureToUow(currentUow, wantedDbContext); 30 | 31 | return wantedDbContext; 32 | } 33 | 34 | private void AddDbTransactionFeatureToUow(IUnitOfWork uow, TDbContext dbContext) 35 | { 36 | string key = $"EFCore - {dbContext.ContextId.InstanceId.ToString()}"; 37 | 38 | var efFeature = (EFTransactionFeature)uow.GetOrAddTransactionFeature(key, new EFTransactionFeature(dbContext)); 39 | 40 | if (IsFeatureNeedOpenTransaction(uow, efFeature)) 41 | { 42 | var dbcontextTransaction = uow.UnitOfWorkOptions.IsolationLevel.HasValue ? 43 | dbContext.Database.BeginTransaction(uow.UnitOfWorkOptions.IsolationLevel.Value) : 44 | dbContext.Database.BeginTransaction(); 45 | 46 | efFeature.SetTransaction(dbcontextTransaction); 47 | } 48 | } 49 | 50 | private bool IsFeatureNeedOpenTransaction(IUnitOfWork uow, EFTransactionFeature efFeature) 51 | { 52 | return !efFeature.IsOpenTransaction; 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /UnitOfWorkDemo/MiCake.Uow.Easy/UnitOfWorkManager.cs: -------------------------------------------------------------------------------- 1 | using MiCake.Core.Abstractions; 2 | using Microsoft.Extensions.DependencyInjection; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Text; 6 | 7 | namespace MiCake.Uow.Easy 8 | { 9 | public class UnitOfWorkManager : IUnitOfWorkManager 10 | { 11 | private IUnitOfWork currentUow; 12 | private bool _isDisposed = false; 13 | 14 | private readonly IServiceProvider _serviceProvider; 15 | 16 | public UnitOfWorkManager( 17 | IServiceProvider serviceProvider) 18 | { 19 | _serviceProvider = serviceProvider; 20 | } 21 | 22 | public IUnitOfWork Create() 23 | { 24 | return Create(new UnitOfWorkOptions()); 25 | } 26 | 27 | public IUnitOfWork Create(UnitOfWorkOptions options) 28 | { 29 | currentUow = CreateNewUnitOfWork(options); 30 | 31 | return currentUow; 32 | } 33 | 34 | public IUnitOfWork GetCurrentUnitOfWork() 35 | { 36 | return currentUow; 37 | } 38 | 39 | //Create a new unitofwork 40 | private IUnitOfWork CreateNewUnitOfWork(UnitOfWorkOptions options) 41 | { 42 | IUnitOfWork result; 43 | 44 | var uowScope = _serviceProvider.CreateScope(); 45 | 46 | try 47 | { 48 | result = uowScope.ServiceProvider.GetRequiredService(); 49 | 50 | if (options != null) 51 | result.SetOptions(options); 52 | 53 | result.DisposeHandler += (sender, args) => 54 | { 55 | uowScope.Dispose(); 56 | currentUow = null; 57 | }; 58 | } 59 | catch (Exception ex) 60 | { 61 | uowScope.Dispose(); 62 | throw ex; 63 | } 64 | 65 | return result; 66 | } 67 | 68 | public void Dispose() 69 | { 70 | if (_isDisposed) 71 | throw new MiCakeException("this manager is already disposed"); 72 | 73 | _isDisposed = true; 74 | 75 | currentUow?.Dispose(); 76 | } 77 | 78 | 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /DomianEventDemo/DomainEventDemo/Entity.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Reflection; 4 | 5 | namespace DomainEventDemo 6 | { 7 | [Serializable] 8 | public abstract class Entity : Entity 9 | { 10 | } 11 | 12 | [Serializable] 13 | public abstract class Entity : IEntity 14 | { 15 | public virtual TKey Id { get; set; } 16 | 17 | protected List _domainEvents = new List(); 18 | 19 | public virtual void AddDomainEvent(IDomainEvent domainEvent) 20 | => _domainEvents.Add(domainEvent); 21 | 22 | public virtual void RemoveDomainEvent(IDomainEvent domainEvent) 23 | => _domainEvents.Remove(domainEvent); 24 | 25 | public List GetDomainEvents() 26 | => _domainEvents; 27 | 28 | public override bool Equals(object obj) 29 | { 30 | if (obj == null || !(obj is Entity)) 31 | { 32 | return false; 33 | } 34 | 35 | //Same instances must be considered as equal 36 | if (ReferenceEquals(this, obj)) 37 | { 38 | return true; 39 | } 40 | 41 | var equalEntity = (Entity)obj; 42 | 43 | if (EntityHelper.HasDefaultId(this) && EntityHelper.HasDefaultId(equalEntity)) 44 | { 45 | return false; 46 | } 47 | 48 | //Compare type 49 | var typeOfThis = GetType().GetTypeInfo(); 50 | var typeOfOther = equalEntity.GetType().GetTypeInfo(); 51 | if (!typeOfThis.IsAssignableFrom(typeOfOther) && !typeOfOther.IsAssignableFrom(typeOfThis)) 52 | { 53 | return false; 54 | } 55 | 56 | return Id.Equals(equalEntity.Id); 57 | } 58 | 59 | public override int GetHashCode() 60 | { 61 | if (Id == null) 62 | { 63 | return 0; 64 | } 65 | 66 | return Id.GetHashCode(); 67 | } 68 | 69 | public static bool operator ==(Entity left, Entity right) 70 | { 71 | if (Equals(left, null)) 72 | { 73 | return Equals(right, null); 74 | } 75 | 76 | return left.Equals(right); 77 | } 78 | 79 | public static bool operator !=(Entity left, Entity right) 80 | { 81 | return !(left == right); 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /UnitOfWorkDemo/MiCake.EFCore.Easy/EFTranscationFeature.cs: -------------------------------------------------------------------------------- 1 | using MiCake.Core.Abstractions; 2 | using MiCake.Uow.Easy; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Storage; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | 8 | namespace MiCake.EFCore.Easy 9 | { 10 | public class EFTransactionFeature : ITransactionFeature 11 | { 12 | public bool IsCommit { get; private set; } 13 | public bool IsRollback { get; private set; } 14 | public bool IsOpenTransaction => _isOpenTransaction; 15 | 16 | private bool _isOpenTransaction; 17 | private bool _isDispose; 18 | private IDbContextTransaction _dbContextTransaction; 19 | private DbContext _dbContext; 20 | 21 | public EFTransactionFeature(DbContext dbContext) 22 | { 23 | _dbContext = dbContext; 24 | } 25 | 26 | public void SetTransaction(IDbContextTransaction dbContextTransaction) 27 | { 28 | if (_isOpenTransaction) 29 | throw new MiCakeException("this transaction feature is already set transaction!"); 30 | 31 | _isOpenTransaction = true; 32 | _dbContextTransaction = dbContextTransaction; 33 | } 34 | 35 | public void Commit() 36 | { 37 | if (IsCommit) 38 | return; 39 | 40 | IsCommit = true; 41 | 42 | _dbContext.SaveChanges(); 43 | _dbContextTransaction?.Commit(); 44 | } 45 | 46 | public async Task CommitAsync(CancellationToken cancellationToken = default) 47 | { 48 | if (IsCommit) 49 | return; 50 | 51 | IsCommit = true; 52 | 53 | await _dbContext.SaveChangesAsync(); 54 | await _dbContextTransaction?.CommitAsync(cancellationToken); 55 | } 56 | 57 | public void Dispose() 58 | { 59 | if (_isDispose) 60 | return; 61 | 62 | _isDispose = true; 63 | 64 | _dbContextTransaction?.Dispose(); 65 | _dbContext?.Dispose(); 66 | } 67 | 68 | public void Rollback() 69 | { 70 | if (IsRollback) 71 | return; 72 | 73 | IsRollback = true; 74 | 75 | _dbContextTransaction?.Rollback(); 76 | } 77 | 78 | public async Task RollbackAsync(CancellationToken cancellationToken = default) 79 | { 80 | if (IsRollback) 81 | return; 82 | 83 | IsRollback = true; 84 | 85 | await _dbContextTransaction?.RollbackAsync(cancellationToken); 86 | } 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015/2017 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # Visual Studio 2017 auto generated files 33 | Generated\ Files/ 34 | 35 | # MSTest test Results 36 | [Tt]est[Rr]esult*/ 37 | [Bb]uild[Ll]og.* 38 | 39 | # NUNIT 40 | *.VisualState.xml 41 | TestResult.xml 42 | 43 | # Build Results of an ATL Project 44 | [Dd]ebugPS/ 45 | [Rr]eleasePS/ 46 | dlldata.c 47 | 48 | # Benchmark Results 49 | BenchmarkDotNet.Artifacts/ 50 | 51 | # .NET Core 52 | project.lock.json 53 | project.fragment.lock.json 54 | artifacts/ 55 | **/Properties/launchSettings.json 56 | 57 | # StyleCop 58 | StyleCopReport.xml 59 | 60 | # Files built by Visual Studio 61 | *_i.c 62 | *_p.c 63 | *_i.h 64 | *.ilk 65 | *.meta 66 | *.obj 67 | *.iobj 68 | *.pch 69 | *.pdb 70 | *.ipdb 71 | *.pgc 72 | *.pgd 73 | *.rsp 74 | *.sbr 75 | *.tlb 76 | *.tli 77 | *.tlh 78 | *.tmp 79 | *.tmp_proj 80 | *.log 81 | *.vspscc 82 | *.vssscc 83 | .builds 84 | *.pidb 85 | *.svclog 86 | *.scc 87 | 88 | # Chutzpah Test files 89 | _Chutzpah* 90 | 91 | # Visual C++ cache files 92 | ipch/ 93 | *.aps 94 | *.ncb 95 | *.opendb 96 | *.opensdf 97 | *.sdf 98 | *.cachefile 99 | *.VC.db 100 | *.VC.VC.opendb 101 | 102 | # Visual Studio profiler 103 | *.psess 104 | *.vsp 105 | *.vspx 106 | *.sap 107 | 108 | # Visual Studio Trace Files 109 | *.e2e 110 | 111 | # TFS 2012 Local Workspace 112 | $tf/ 113 | 114 | # Guidance Automation Toolkit 115 | *.gpState 116 | 117 | # ReSharper is a .NET coding add-in 118 | _ReSharper*/ 119 | *.[Rr]e[Ss]harper 120 | *.DotSettings.user 121 | 122 | # JustCode is a .NET coding add-in 123 | .JustCode 124 | 125 | # TeamCity is a build add-in 126 | _TeamCity* 127 | 128 | # DotCover is a Code Coverage Tool 129 | *.dotCover 130 | 131 | # AxoCover is a Code Coverage Tool 132 | .axoCover/* 133 | !.axoCover/settings.json 134 | 135 | # Visual Studio code coverage results 136 | *.coverage 137 | *.coveragexml 138 | 139 | # NCrunch 140 | _NCrunch_* 141 | .*crunch*.local.xml 142 | nCrunchTemp_* 143 | 144 | # MightyMoose 145 | *.mm.* 146 | AutoTest.Net/ 147 | 148 | # Web workbench (sass) 149 | .sass-cache/ 150 | 151 | # Installshield output folder 152 | [Ee]xpress/ 153 | 154 | # DocProject is a documentation generator add-in 155 | DocProject/buildhelp/ 156 | DocProject/Help/*.HxT 157 | DocProject/Help/*.HxC 158 | DocProject/Help/*.hhc 159 | DocProject/Help/*.hhk 160 | DocProject/Help/*.hhp 161 | DocProject/Help/Html2 162 | DocProject/Help/html 163 | 164 | # Click-Once directory 165 | publish/ 166 | 167 | # Publish Web Output 168 | *.[Pp]ublish.xml 169 | *.azurePubxml 170 | # Note: Comment the next line if you want to checkin your web deploy settings, 171 | # but database connection strings (with potential passwords) will be unencrypted 172 | *.pubxml 173 | *.publishproj 174 | 175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 176 | # checkin your Azure Web App publish settings, but sensitive information contained 177 | # in these scripts will be unencrypted 178 | PublishScripts/ 179 | 180 | # NuGet Packages 181 | *.nupkg 182 | # The packages folder can be ignored because of Package Restore 183 | **/[Pp]ackages/* 184 | # except build/, which is used as an MSBuild target. 185 | !**/[Pp]ackages/build/ 186 | # Uncomment if necessary however generally it will be regenerated when needed 187 | #!**/[Pp]ackages/repositories.config 188 | # NuGet v3's project.json files produces more ignorable files 189 | *.nuget.props 190 | *.nuget.targets 191 | 192 | # Microsoft Azure Build Output 193 | csx/ 194 | *.build.csdef 195 | 196 | # Microsoft Azure Emulator 197 | ecf/ 198 | rcf/ 199 | 200 | # Windows Store app package directories and files 201 | AppPackages/ 202 | BundleArtifacts/ 203 | Package.StoreAssociation.xml 204 | _pkginfo.txt 205 | *.appx 206 | 207 | # Visual Studio cache files 208 | # files ending in .cache can be ignored 209 | *.[Cc]ache 210 | # but keep track of directories ending in .cache 211 | !*.[Cc]ache/ 212 | 213 | # Others 214 | ClientBin/ 215 | ~$* 216 | *~ 217 | *.dbmdl 218 | *.dbproj.schemaview 219 | *.jfm 220 | *.pfx 221 | *.publishsettings 222 | orleans.codegen.cs 223 | 224 | # Including strong name files can present a security risk 225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 226 | #*.snk 227 | 228 | # Since there are multiple workflows, uncomment next line to ignore bower_components 229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 230 | #bower_components/ 231 | 232 | # RIA/Silverlight projects 233 | Generated_Code/ 234 | 235 | # Backup & report files from converting an old project file 236 | # to a newer Visual Studio version. Backup files are not needed, 237 | # because we have git ;-) 238 | _UpgradeReport_Files/ 239 | Backup*/ 240 | UpgradeLog*.XML 241 | UpgradeLog*.htm 242 | ServiceFabricBackup/ 243 | *.rptproj.bak 244 | 245 | # SQL Server files 246 | *.mdf 247 | *.ldf 248 | *.ndf 249 | 250 | # Business Intelligence projects 251 | *.rdl.data 252 | *.bim.layout 253 | *.bim_*.settings 254 | *.rptproj.rsuser 255 | 256 | # Microsoft Fakes 257 | FakesAssemblies/ 258 | 259 | # GhostDoc plugin setting file 260 | *.GhostDoc.xml 261 | 262 | # Node.js Tools for Visual Studio 263 | .ntvs_analysis.dat 264 | node_modules/ 265 | 266 | # Visual Studio 6 build log 267 | *.plg 268 | 269 | # Visual Studio 6 workspace options file 270 | *.opt 271 | 272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 273 | *.vbw 274 | 275 | # Visual Studio LightSwitch build output 276 | **/*.HTMLClient/GeneratedArtifacts 277 | **/*.DesktopClient/GeneratedArtifacts 278 | **/*.DesktopClient/ModelManifest.xml 279 | **/*.Server/GeneratedArtifacts 280 | **/*.Server/ModelManifest.xml 281 | _Pvt_Extensions 282 | 283 | # Paket dependency manager 284 | .paket/paket.exe 285 | paket-files/ 286 | 287 | # FAKE - F# Make 288 | .fake/ 289 | 290 | # JetBrains Rider 291 | .idea/ 292 | *.sln.iml 293 | 294 | # CodeRush 295 | .cr/ 296 | 297 | # Python Tools for Visual Studio (PTVS) 298 | __pycache__/ 299 | *.pyc 300 | 301 | # Cake - Uncomment if you are using it 302 | # tools/** 303 | # !tools/packages.config 304 | 305 | # Tabs Studio 306 | *.tss 307 | 308 | # Telerik's JustMock configuration file 309 | *.jmconfig 310 | 311 | # BizTalk build output 312 | *.btp.cs 313 | *.btm.cs 314 | *.odx.cs 315 | *.xsd.cs 316 | 317 | # OpenCover UI analysis results 318 | OpenCover/ 319 | 320 | # Azure Stream Analytics local run output 321 | ASALocalRun/ 322 | 323 | # MSBuild Binary and Structured Log 324 | *.binlog 325 | 326 | # NVidia Nsight GPU debugger configuration file 327 | *.nvuser 328 | 329 | # MFractors (Xamarin productivity tool) working folder 330 | .mfractor/ 331 | /BaseMiCakeApplication/Migrations 332 | -------------------------------------------------------------------------------- /DomianEventDemo/DomainEventDemo/Registrar/DomainEventHandlerRegistrar.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using Microsoft.Extensions.DependencyInjection.Extensions; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Reflection; 7 | 8 | namespace DomainEventDemo.Registrar 9 | { 10 | public static class DomainEventHandlerRegistrar 11 | { 12 | //Base on MediatR.Registration 13 | //see https://github.com/jbogard/MediatR.Extensions.Microsoft.DependencyInjection 14 | public static void ResigterDomainEventHandler(this IServiceCollection services, Assembly[] assemblies) 15 | { 16 | // var assemblies = miCakeModules.GetAssemblies(false).ToList(); 17 | 18 | ConnectImplementationsToTypesClosing(typeof(IDomainEventHandler<>), services, assemblies, true); 19 | } 20 | 21 | /// 22 | /// Helper method use to differentiate behavior between request handlers and notification handlers. 23 | /// 24 | /// 25 | /// 26 | /// 27 | /// 28 | private static void ConnectImplementationsToTypesClosing(Type openRequestInterface, 29 | IServiceCollection services, 30 | IEnumerable assembliesToScan, 31 | bool addIfAlreadyExists) 32 | { 33 | var concretions = new List(); 34 | var interfaces = new List(); 35 | foreach (var type in assembliesToScan.SelectMany(a => a.DefinedTypes).Where(t => !t.IsOpenGeneric())) 36 | { 37 | var interfaceTypes = type.FindInterfacesThatClose(openRequestInterface).ToArray(); 38 | if (!interfaceTypes.Any()) continue; 39 | 40 | if (type.IsConcrete()) 41 | { 42 | concretions.Add(type); 43 | } 44 | 45 | foreach (var interfaceType in interfaceTypes) 46 | { 47 | interfaces.Fill(interfaceType); 48 | } 49 | } 50 | 51 | foreach (var @interface in interfaces) 52 | { 53 | var exactMatches = concretions.Where(x => x.CanBeCastTo(@interface)).ToList(); 54 | if (addIfAlreadyExists) 55 | { 56 | foreach (var type in exactMatches) 57 | { 58 | services.AddTransient(@interface, type); 59 | } 60 | } 61 | else 62 | { 63 | if (exactMatches.Count > 1) 64 | { 65 | exactMatches.RemoveAll(m => !IsMatchingWithInterface(m, @interface)); 66 | } 67 | 68 | foreach (var type in exactMatches) 69 | { 70 | services.TryAddTransient(@interface, type); 71 | } 72 | } 73 | 74 | if (!@interface.IsOpenGeneric()) 75 | { 76 | AddConcretionsThatCouldBeClosed(@interface, concretions, services); 77 | } 78 | } 79 | } 80 | 81 | private static bool IsMatchingWithInterface(Type handlerType, Type handlerInterface) 82 | { 83 | if (handlerType == null || handlerInterface == null) 84 | { 85 | return false; 86 | } 87 | 88 | if (handlerType.IsInterface) 89 | { 90 | if (handlerType.GenericTypeArguments.SequenceEqual(handlerInterface.GenericTypeArguments)) 91 | { 92 | return true; 93 | } 94 | } 95 | else 96 | { 97 | return IsMatchingWithInterface(handlerType.GetInterface(handlerInterface.Name), handlerInterface); 98 | } 99 | 100 | return false; 101 | } 102 | 103 | private static void AddConcretionsThatCouldBeClosed(Type @interface, List concretions, IServiceCollection services) 104 | { 105 | foreach (var type in concretions 106 | .Where(x => x.IsOpenGeneric() && x.CouldCloseTo(@interface))) 107 | { 108 | try 109 | { 110 | services.TryAddTransient(@interface, type.MakeGenericType(@interface.GenericTypeArguments)); 111 | } 112 | catch (Exception) 113 | { 114 | } 115 | } 116 | } 117 | 118 | private static bool CouldCloseTo(this Type openConcretion, Type closedInterface) 119 | { 120 | var openInterface = closedInterface.GetGenericTypeDefinition(); 121 | var arguments = closedInterface.GenericTypeArguments; 122 | 123 | var concreteArguments = openConcretion.GenericTypeArguments; 124 | return arguments.Length == concreteArguments.Length && openConcretion.CanBeCastTo(openInterface); 125 | } 126 | 127 | private static bool CanBeCastTo(this Type pluggedType, Type pluginType) 128 | { 129 | if (pluggedType == null) return false; 130 | 131 | if (pluggedType == pluginType) return true; 132 | 133 | return pluginType.GetTypeInfo().IsAssignableFrom(pluggedType.GetTypeInfo()); 134 | } 135 | 136 | private static bool IsOpenGeneric(this Type type) 137 | { 138 | return type.GetTypeInfo().IsGenericTypeDefinition || type.GetTypeInfo().ContainsGenericParameters; 139 | } 140 | 141 | private static IEnumerable FindInterfacesThatClose(this Type pluggedType, Type templateType) 142 | { 143 | return FindInterfacesThatClosesCore(pluggedType, templateType).Distinct(); 144 | } 145 | 146 | private static IEnumerable FindInterfacesThatClosesCore(Type pluggedType, Type templateType) 147 | { 148 | if (pluggedType == null) yield break; 149 | 150 | if (!pluggedType.IsConcrete()) yield break; 151 | 152 | if (templateType.GetTypeInfo().IsInterface) 153 | { 154 | foreach ( 155 | var interfaceType in 156 | pluggedType.GetInterfaces() 157 | .Where(type => type.GetTypeInfo().IsGenericType && (type.GetGenericTypeDefinition() == templateType))) 158 | { 159 | yield return interfaceType; 160 | } 161 | } 162 | else if (pluggedType.GetTypeInfo().BaseType.GetTypeInfo().IsGenericType && 163 | (pluggedType.GetTypeInfo().BaseType.GetGenericTypeDefinition() == templateType)) 164 | { 165 | yield return pluggedType.GetTypeInfo().BaseType; 166 | } 167 | 168 | if (pluggedType.GetTypeInfo().BaseType == typeof(object)) yield break; 169 | 170 | foreach (var interfaceType in FindInterfacesThatClosesCore(pluggedType.GetTypeInfo().BaseType, templateType)) 171 | { 172 | yield return interfaceType; 173 | } 174 | } 175 | 176 | private static bool IsConcrete(this Type type) 177 | { 178 | return !type.GetTypeInfo().IsAbstract && !type.GetTypeInfo().IsInterface; 179 | } 180 | 181 | private static void Fill(this IList list, T value) 182 | { 183 | if (list.Contains(value)) return; 184 | list.Add(value); 185 | } 186 | } 187 | } 188 | -------------------------------------------------------------------------------- /UnitOfWorkDemo/MiCake.Uow.Easy/UnitOfWork.cs: -------------------------------------------------------------------------------- 1 | using JetBrains.Annotations; 2 | using MiCake.Core.Abstractions; 3 | using MiCake.Core.Util.Collections; 4 | using Microsoft.Extensions.Options; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Threading; 8 | using System.Threading.Tasks; 9 | 10 | namespace MiCake.Uow.Easy 11 | { 12 | public class UnitOfWork : IUnitOfWork 13 | { 14 | public Guid ID { get; private set; } 15 | public bool IsDisposed { get; private set; } 16 | public event EventHandler DisposeHandler; 17 | public UnitOfWorkOptions UnitOfWorkOptions { get; private set; } 18 | public IServiceProvider ServiceProvider { get; private set; } 19 | 20 | private readonly Dictionary _transactionFeatures; 21 | private Action _saveChangedAction; 22 | private Action _rollBackedAction; 23 | private bool _isSaveChanged; 24 | private bool _isRollbacked; 25 | 26 | public UnitOfWork( 27 | IServiceProvider serviceProvider) 28 | { 29 | ID = Guid.NewGuid(); 30 | ServiceProvider = serviceProvider; 31 | 32 | _transactionFeatures = new Dictionary(); 33 | } 34 | 35 | public virtual ITransactionFeature GetOrAddTransactionFeature( 36 | [NotNull]string key, 37 | [NotNull] ITransactionFeature transcationFeature) 38 | { 39 | if (_transactionFeatures.ContainsKey(key)) 40 | return _transactionFeatures.GetValueOrDefault(key); 41 | 42 | _transactionFeatures.Add(key, transcationFeature); 43 | return transcationFeature; 44 | } 45 | 46 | public virtual ITransactionFeature GetTransactionFeature([NotNull]string key) 47 | { 48 | return _transactionFeatures.GetValueOrDefault(key); 49 | } 50 | 51 | public virtual void RemoveTransaction([NotNull]string key) 52 | { 53 | _transactionFeatures.Remove(key); 54 | } 55 | 56 | public virtual void RegisteTranasctionFeature( 57 | [NotNull]string key, 58 | [NotNull]ITransactionFeature transcationFeature) 59 | { 60 | if (_transactionFeatures.ContainsKey(key)) 61 | return; 62 | 63 | _transactionFeatures.Add(key, transcationFeature); 64 | } 65 | 66 | public virtual void Rollback() 67 | { 68 | if (_isRollbacked) 69 | throw new InvalidOperationException("this unit work is already execute Rollback method."); 70 | 71 | var rollBackExceptions = new List(); 72 | 73 | _isRollbacked = true; 74 | 75 | foreach (var transactionFeature in _transactionFeatures.Values) 76 | { 77 | try 78 | { 79 | transactionFeature.Rollback(); 80 | } 81 | catch (Exception ex) 82 | { 83 | // Capture any errors that happen during savechanges 84 | rollBackExceptions.Add(ex); 85 | } 86 | } 87 | 88 | if (rollBackExceptions.Count > 0) 89 | throw new AggregateException(rollBackExceptions); 90 | 91 | _rollBackedAction?.Invoke(); 92 | } 93 | 94 | public virtual async Task RollbackAsync(CancellationToken cancellationToken = default) 95 | { 96 | if (_isRollbacked) 97 | throw new InvalidOperationException("this unit work is already execute Rollback method."); 98 | 99 | var rollBackExceptions = new List(); 100 | 101 | _isRollbacked = true; 102 | 103 | foreach (var transactionFeature in _transactionFeatures.Values) 104 | { 105 | try 106 | { 107 | await transactionFeature.RollbackAsync(cancellationToken); 108 | } 109 | catch (Exception ex) 110 | { 111 | // Capture any errors that happen during savechanges 112 | rollBackExceptions.Add(ex); 113 | } 114 | } 115 | 116 | if (rollBackExceptions.Count > 0) 117 | throw new AggregateException(rollBackExceptions); 118 | 119 | _rollBackedAction?.Invoke(); 120 | } 121 | 122 | public virtual void SaveChanges() 123 | { 124 | if (_isSaveChanged) 125 | throw new InvalidOperationException("this unit work is already execute SaveChanges method."); 126 | 127 | var saveExceptions = new List(); 128 | 129 | _isSaveChanged = true; 130 | 131 | foreach (var transactionFeature in _transactionFeatures.Values) 132 | { 133 | try 134 | { 135 | transactionFeature.Commit(); 136 | } 137 | catch (Exception ex) 138 | { 139 | // Capture any errors that happen during savechanges 140 | saveExceptions.Add(ex); 141 | } 142 | } 143 | 144 | if (saveExceptions.Count > 0) 145 | throw new AggregateException(saveExceptions); 146 | 147 | _saveChangedAction?.Invoke(); 148 | } 149 | 150 | public virtual async Task SaveChangesAsync(CancellationToken cancellationToken = default) 151 | { 152 | if (_isSaveChanged) 153 | throw new InvalidOperationException("this unit work is already execute SaveChanges method."); 154 | 155 | var saveExceptions = new List(); 156 | 157 | _isSaveChanged = true; 158 | 159 | foreach (var transactionFeature in _transactionFeatures.Values) 160 | { 161 | try 162 | { 163 | await transactionFeature.CommitAsync(cancellationToken); 164 | } 165 | catch (Exception ex) 166 | { 167 | // Capture any errors that happen during savechanges 168 | saveExceptions.Add(ex); 169 | } 170 | } 171 | 172 | if (saveExceptions.Count > 0) 173 | throw new AggregateException(saveExceptions); 174 | 175 | _saveChangedAction?.Invoke(); 176 | } 177 | 178 | public void Dispose() 179 | { 180 | if (IsDisposed) 181 | return; 182 | 183 | IsDisposed = true; 184 | 185 | var disposeExceptions = new List(); 186 | 187 | foreach (var transactionFeature in _transactionFeatures.Values) 188 | { 189 | try 190 | { 191 | transactionFeature.Dispose(); 192 | } 193 | catch (Exception ex) 194 | { 195 | disposeExceptions.Add(ex); 196 | } 197 | } 198 | 199 | if (disposeExceptions.Count > 0) 200 | throw new AggregateException(disposeExceptions); 201 | 202 | DisposeHandler.Invoke(this, this); 203 | } 204 | 205 | public virtual void OnSaveChanged(Action action) 206 | { 207 | _saveChangedAction += action; 208 | } 209 | 210 | public virtual void OnRollBacked(Action action) 211 | { 212 | _rollBackedAction += action 213 | ; 214 | } 215 | 216 | public void SetOptions(UnitOfWorkOptions options) 217 | { 218 | UnitOfWorkOptions = options.Clone(); 219 | } 220 | } 221 | } 222 | --------------------------------------------------------------------------------