├── .dockerignore ├── .gitattributes ├── .gitignore ├── Example ├── Identity.API │ ├── AppSettings.cs │ ├── Controllers │ │ ├── AccountController.cs │ │ ├── HomeController.cs │ │ └── ValuesController.cs │ ├── Dockerfile │ ├── Identity.API.csproj │ ├── Identity.API.xml │ ├── Init │ │ ├── ConfigurationDbContextSeed.cs │ │ ├── IdentityServerSeed.cs │ │ └── IdentityUserDbContextSeed.cs │ ├── Migrations │ │ ├── ConfigurationDbContexts │ │ │ ├── 20181211095757_initial.Designer.cs │ │ │ ├── 20181211095757_initial.cs │ │ │ └── ConfigurationDbContextModelSnapshot.cs │ │ ├── IdentityUserDbContexts │ │ │ ├── 20181217113104_Initial.Designer.cs │ │ │ ├── 20181217113104_Initial.cs │ │ │ └── IdentityUserDbContextModelSnapshot.cs │ │ └── PersistedGrantDbContexts │ │ │ ├── 20181211095830_initial.Designer.cs │ │ │ ├── 20181211095830_initial.cs │ │ │ └── PersistedGrantDbContextModelSnapshot.cs │ ├── Models │ │ └── LoginViewModel.cs │ ├── Program.cs │ ├── Properties │ │ ├── PublishProfiles │ │ │ └── FolderProfile.pubxml │ │ └── launchSettings.json │ ├── Startup.cs │ ├── appsettings.Development.json │ ├── appsettings.Production.json │ ├── appsettings.json │ ├── cas.clientservice.cer │ ├── cas.clientservice.key │ └── cas.clientservice.pfx ├── Order.API │ ├── Appsettings.cs │ ├── Controllers │ │ ├── AccountController.cs │ │ └── OrderController.cs │ ├── Dockerfile │ ├── Migrations │ │ ├── 20181202061912_initial.Designer.cs │ │ ├── 20181202061912_initial.cs │ │ └── OrderDbContextModelSnapshot.cs │ ├── Models │ │ ├── LoginViewModel.cs │ │ └── OrderAddedViewModel.cs │ ├── Order.API.csproj │ ├── Order.API.xml │ ├── Program.cs │ ├── Properties │ │ ├── PublishProfiles │ │ │ └── FolderProfile.pubxml │ │ └── launchSettings.json │ ├── Startup.cs │ ├── appsettings.Development.json │ └── appsettings.json └── Order.Domain │ ├── Aggregates │ ├── BuyerAggregate │ │ ├── Buyer.cs │ │ ├── PaymentMethod.cs │ │ └── PaymentType.cs │ └── OrderAggregate │ │ ├── Address.cs │ │ ├── Order.cs │ │ ├── OrderItem.cs │ │ └── OrderStatus.cs │ ├── Application │ └── Commands │ │ ├── CreateOrderCommand.cs │ │ └── CreateOrderCommandHandler.cs │ ├── DbContexts │ ├── OrderDbContext.cs │ └── OrderDbContextSeed.cs │ ├── EntityConfigurations │ ├── BuyerEntityTypeConfiguration.cs │ ├── OrderEntityTypeConfiguration.cs │ ├── OrderItemEntityTypeConfiguration.cs │ ├── OrderStatusEntityTypeConfiguration.cs │ ├── PaymentMethodEntityTypeConfiguration.cs │ └── PaymentTypeEntityTypeConfiguration.cs │ ├── Events │ ├── BuyerAndPaymentMethodVerifiedDomainEvent.cs │ ├── DomainEventHandlers │ │ ├── OrderStartedDomainEventHandler.cs │ │ └── UpdateOrderWhenBuyerAndPaymentMethodVerifiedDomainEventHandler.cs │ └── OrderStartedDomainEvent.cs │ └── Order.Domain.csproj ├── JieDDDFramework.Core ├── Configures │ ├── BaseConfig.cs │ ├── ConfigureExtensions.cs │ ├── Connectionstrings.cs │ └── Logging.cs ├── Domain │ ├── Entity.cs │ ├── Entity`1.cs │ ├── Enumeration.cs │ ├── IAggregateRoot.cs │ ├── IEntity.cs │ ├── IRepository.cs │ ├── IUnitOfWork.cs │ └── ValueObject.cs ├── EntitySpecifications │ ├── ICreatedTimeState.cs │ ├── IDeletedState.cs │ └── IModificationState.cs ├── Exceptions │ ├── DomainException.cs │ ├── ExceptionExtension.cs │ ├── KnownException.cs │ ├── ServiceAuthenticationException.cs │ └── Utilities │ │ └── Check.cs ├── Extensions │ ├── LinqSelectExtensions.cs │ └── TypeExtensions.cs ├── JieDDDFramework.Core.csproj ├── MediatR │ ├── Behaviors │ │ ├── LoggingBehavior.cs │ │ └── ValidatorBehavior.cs │ ├── MediatRExtensions.cs │ └── NoMediator.cs ├── Models │ ├── ApiResult.cs │ ├── IPagedList`1.cs │ ├── IPagerBase.cs │ ├── IPagerQuery.cs │ ├── IResult.cs │ ├── PageOrders.cs │ ├── PagedList`1.cs │ └── Result.cs └── RequestProvider │ ├── HttpRequestExceptionEx.cs │ ├── IRequestProvider.cs │ └── RequestProvider.cs ├── JieDDDFramework.Data.EntityFramework ├── AopConfigurations │ ├── EFInterceptor.cs │ └── ServiceContainerExtensions.cs ├── DbContext │ └── DomainDbContext.cs ├── EntitySpecificationExtensions.cs ├── JieDDDFramework.Data.EntityFramework.csproj ├── MediatorExtension.cs ├── Migrate │ ├── IDbContextSeed.cs │ ├── MigrateBuilder.cs │ ├── MigrateBuilderExtensions.cs │ ├── MigrateConfigurations.cs │ └── MigrateDbContextExtensions.cs ├── ModelConfigurations │ ├── DDDEntityTypeConfiguration.cs │ ├── DefaultModelConfigurationProvider.cs │ ├── IModelConfigurationProvider.cs │ ├── ModelBuilderExtensions.cs │ ├── ModelConfigurationExtensions.cs │ ├── ModelConfigurationOption.cs │ └── Services │ │ ├── DefaultAutoApplyConfigurationService.cs │ │ ├── DefaultFixModelConfigurationService.cs │ │ ├── DefaultGlobalFilterService.cs │ │ ├── IAutoApplyConfigurationService.cs │ │ ├── IFixModelConfigurationService.cs │ │ └── IGlobalFilterService.cs ├── QueryablePageListExtensions.cs ├── Repositories │ └── Repository`1.cs └── RepositoryExtensions.cs ├── JieDDDFramework.Data ├── JieDDDFramework.Data.csproj └── Repository │ └── IRepositoryBase`1.cs ├── JieDDDFramework.Service ├── Dtos │ ├── IDto.cs │ ├── IRequest.cs │ └── IResponse.cs ├── IQueryService.cs ├── IService.cs ├── JieDDDFramework.Service.csproj └── Operations │ ├── IGetAll.cs │ ├── IGetAllAsync.cs │ ├── IGetById.cs │ ├── IGetByIdAsync.cs │ ├── IPageQuery.cs │ └── IPageQueryAsync.cs ├── JieDDDFramework.Web ├── BaseController.cs ├── Filters │ ├── HttpGlobalExceptionFilter.cs │ ├── MvcFilterExtensions.cs │ └── ValidateModelStateFilter.cs ├── JieDDDFramework.Web.csproj ├── ModelValidate │ ├── ModelResultValidatorInterceptor.cs │ └── ValidatorAttribute.cs ├── Models │ ├── ModelErrorResult.cs │ └── PagedCriteria.cs └── Validate │ ├── FluentValidationExtensions.cs │ └── PagedCriteriaValidator.cs ├── JieDDDFramework.sln ├── LICENSE ├── Module └── JieDDDFramework.Module.Identity │ ├── Data │ └── IdentityUserDbContext.cs │ ├── IdentityServerExtensions.cs │ ├── JieDDDFramework.Module.Identity.csproj │ ├── JwtSettings.cs │ ├── Models │ └── ApplicationUser.cs │ └── Services │ ├── ILoginService.cs │ ├── IRedirectService.cs │ ├── IdentityLoginService.cs │ ├── ProfileService.cs │ └── RedirectService.cs ├── README.md ├── _config.yml └── docs ├── Untitled Diagram.drawio └── pic1.png /.dockerignore: -------------------------------------------------------------------------------- 1 | .dockerignore 2 | .env 3 | .git 4 | .gitignore 5 | .vs 6 | .vscode 7 | */bin 8 | */obj 9 | **/.toolstarget -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /.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 | *.publishsettings 194 | node_modules/ 195 | orleans.codegen.cs 196 | 197 | # Since there are multiple workflows, uncomment next line to ignore bower_components 198 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 199 | #bower_components/ 200 | 201 | # RIA/Silverlight projects 202 | Generated_Code/ 203 | 204 | # Backup & report files from converting an old project file 205 | # to a newer Visual Studio version. Backup files are not needed, 206 | # because we have git ;-) 207 | _UpgradeReport_Files/ 208 | Backup*/ 209 | UpgradeLog*.XML 210 | UpgradeLog*.htm 211 | 212 | # SQL Server files 213 | *.mdf 214 | *.ldf 215 | 216 | # Business Intelligence projects 217 | *.rdl.data 218 | *.bim.layout 219 | *.bim_*.settings 220 | 221 | # Microsoft Fakes 222 | FakesAssemblies/ 223 | 224 | # GhostDoc plugin setting file 225 | *.GhostDoc.xml 226 | 227 | # Node.js Tools for Visual Studio 228 | .ntvs_analysis.dat 229 | 230 | # Visual Studio 6 build log 231 | *.plg 232 | 233 | # Visual Studio 6 workspace options file 234 | *.opt 235 | 236 | # Visual Studio LightSwitch build output 237 | **/*.HTMLClient/GeneratedArtifacts 238 | **/*.DesktopClient/GeneratedArtifacts 239 | **/*.DesktopClient/ModelManifest.xml 240 | **/*.Server/GeneratedArtifacts 241 | **/*.Server/ModelManifest.xml 242 | _Pvt_Extensions 243 | 244 | # Paket dependency manager 245 | .paket/paket.exe 246 | paket-files/ 247 | 248 | # FAKE - F# Make 249 | .fake/ 250 | 251 | # JetBrains Rider 252 | .idea/ 253 | *.sln.iml 254 | 255 | # CodeRush 256 | .cr/ 257 | 258 | # Python Tools for Visual Studio (PTVS) 259 | __pycache__/ 260 | *.pyc -------------------------------------------------------------------------------- /Example/Identity.API/AppSettings.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using JieDDDFramework.Core.Configures; 6 | 7 | namespace Identity.API 8 | { 9 | public class AppSettings : BaseConfig 10 | { 11 | public Certificates Certificates { get; set; } 12 | } 13 | 14 | public class Certificates 15 | { 16 | public string CerPath { get; set; } 17 | public string Password { get; set; } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Example/Identity.API/Controllers/AccountController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text.Encodings.Web; 5 | using System.Threading.Tasks; 6 | using Identity.API.Models; 7 | using IdentityModel.Client; 8 | using IdentityServer4.Services; 9 | using JieDDDFramework.Module.Identity; 10 | using JieDDDFramework.Module.Identity.Models; 11 | using JieDDDFramework.Web; 12 | using JieDDDFramework.Web.ModelValidate; 13 | using Microsoft.AspNetCore.Authentication; 14 | using Microsoft.AspNetCore.Authorization; 15 | using Microsoft.AspNetCore.Identity; 16 | using Microsoft.AspNetCore.Mvc; 17 | using Microsoft.Extensions.Options; 18 | 19 | namespace Identity.API.Controllers 20 | { 21 | [Route("api/[controller]/[action]")] 22 | public class AccountController : BaseController 23 | { 24 | private readonly UserManager _userManager; 25 | private readonly SignInManager _signInManager; 26 | private readonly IIdentityServerInteractionService _interaction; 27 | private readonly JwtSettings _jwtSettings; 28 | 29 | public AccountController(UserManager userManager, SignInManager signInManager, IIdentityServerInteractionService interaction, IOptions jwtSettings) 30 | { 31 | _userManager = userManager; 32 | _signInManager = signInManager; 33 | _interaction = interaction; 34 | _jwtSettings = jwtSettings.Value; 35 | } 36 | 37 | [HttpGet] 38 | public async Task Login(string returnUrl) 39 | { 40 | var context = await _interaction.GetAuthorizationContextAsync(returnUrl); 41 | if (context?.IdP != null) 42 | { 43 | return Redirect(UrlEncoder.Default.Encode(returnUrl)); 44 | } 45 | 46 | return await Login(new LoginViewModel() 47 | { 48 | ReturnUrl = returnUrl, 49 | Password = "123456", 50 | Email = "demouser@xx.com", 51 | RememberMe = true 52 | }); 53 | } 54 | 55 | /// 56 | /// 登录 57 | /// 58 | /// 59 | /// { 60 | /// "email":"demouser@xx.com", 61 | /// "password":"123456" 62 | /// } 63 | /// 64 | /// 65 | /// 66 | [HttpPost] 67 | public async Task Login([FromBody, Validator] LoginViewModel model) 68 | { 69 | var user = await _userManager.FindByEmailAsync(model.Email); 70 | if (user != null && await _userManager.CheckPasswordAsync(user, model.Password)) 71 | { 72 | await _signInManager.SignInAsync(user, model.RememberMe); 73 | if (_interaction.IsValidReturnUrl(model.ReturnUrl)) 74 | { 75 | return Redirect(model.ReturnUrl); 76 | } 77 | return Redirect("~/"); 78 | } 79 | return Redirect("~/"); 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /Example/Identity.API/Controllers/HomeController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Mvc; 6 | 7 | namespace Identity.API.Controllers 8 | { 9 | public class HomeController:Controller 10 | { 11 | public IActionResult Index() 12 | { 13 | return Redirect("/swagger/"); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Example/Identity.API/Controllers/ValuesController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Net; 5 | using System.Threading.Tasks; 6 | using Microsoft.AspNetCore.Mvc; 7 | 8 | namespace Identity.API.Controllers 9 | { 10 | [Route("api/[controller]")] 11 | [ApiController] 12 | public class ValuesController : ControllerBase 13 | { 14 | /// 15 | /// GET api/values 16 | /// 17 | /// 18 | [HttpGet] 19 | [ProducesResponseType(typeof(IEnumerable), (int)HttpStatusCode.OK)] 20 | public ActionResult> Get() 21 | { 22 | return new string[] { "value1", "value2" }; 23 | } 24 | 25 | // GET api/values/5 26 | [HttpGet("{id}")] 27 | public ActionResult Get(int id) 28 | { 29 | return "value"; 30 | } 31 | 32 | // POST api/values 33 | [HttpPost] 34 | public void Post([FromBody] string value) 35 | { 36 | } 37 | 38 | // PUT api/values/5 39 | [HttpPut("{id}")] 40 | public void Put(int id, [FromBody] string value) 41 | { 42 | } 43 | 44 | // DELETE api/values/5 45 | [HttpDelete("{id}")] 46 | public void Delete(int id) 47 | { 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Example/Identity.API/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM microsoft/dotnet:2.1-aspnetcore-runtime AS base 2 | WORKDIR /app 3 | EXPOSE 80 4 | 5 | FROM microsoft/dotnet:2.1-sdk AS build 6 | WORKDIR /src 7 | COPY ["Identity.API/Identity.API.csproj", "Identity.API/"] 8 | RUN dotnet restore "Identity.API/Identity.API.csproj" 9 | COPY . . 10 | WORKDIR "/src/Identity.API" 11 | RUN dotnet build "Identity.API.csproj" -c Release -o /app 12 | 13 | FROM build AS publish 14 | RUN dotnet publish "Identity.API.csproj" -c Release -o /app 15 | 16 | FROM base AS final 17 | WORKDIR /app 18 | COPY --from=publish /app . 19 | ENTRYPOINT ["dotnet", "Identity.API.dll"] -------------------------------------------------------------------------------- /Example/Identity.API/Identity.API.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netcoreapp2.2 5 | Linux 6 | 97fe7db2-0464-43cd-917b-78e82743e8a5 7 | 8 | 9 | 10 | C:\Users\feiji\source\repos\JieDDDFramework\Example\Identity.API\Identity.API.xml 11 | 1701;1702;1591 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | ..\..\..\..\..\..\..\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.aspnetcore.authentication.jwtbearer\2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.Authentication.JwtBearer.dll 35 | 36 | 37 | ..\..\..\..\..\.nuget\packages\microsoft.aspnetcore.dataprotection.redis\0.4.1\lib\netstandard2.0\Microsoft.AspNetCore.DataProtection.Redis.dll 38 | 39 | 40 | 41 | 42 | 43 | PreserveNewest 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /Example/Identity.API/Identity.API.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Identity.API 5 | 6 | 7 | 8 | 9 | 登录 10 | 11 | 12 | { 13 | "email":"demouser@xx.com", 14 | "password":"123456" 15 | } 16 | 17 | 18 | 19 | 20 | 21 | 22 | GET api/values 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /Example/Identity.API/Init/ConfigurationDbContextSeed.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using IdentityServer4.EntityFramework.DbContexts; 6 | using IdentityServer4.EntityFramework.Mappers; 7 | using JieDDDFramework.Data.EntityFramework.Migrate; 8 | using JieDDDFramework.Module.Identity; 9 | using Microsoft.Extensions.Configuration; 10 | using Microsoft.Extensions.Options; 11 | 12 | namespace Identity.API.Init 13 | { 14 | public class ConfigurationDbContextSeed : IDbContextSeed 15 | { 16 | private readonly IConfiguration _configuration; 17 | 18 | public ConfigurationDbContextSeed(IConfiguration configuration) 19 | { 20 | _configuration = configuration; 21 | } 22 | public async Task SeedAsync(ConfigurationDbContext context) 23 | { 24 | var clientUrls = new Dictionary(); 25 | 26 | clientUrls.Add("Mvc", _configuration.GetValue("MvcClient")); 27 | clientUrls.Add("OrderApi", _configuration.GetValue("OrderClient")); 28 | clientUrls.Add("IdentityApi", _configuration.GetValue("IdentityClient")); 29 | var secret = _configuration.GetSection("JwtSettings").GetValue("SecretKey"); 30 | #if DEBUG 31 | var clients = context.Clients.ToList(); 32 | context.RemoveRange(clients); 33 | var apiResources = context.ApiResources.ToList(); 34 | context.RemoveRange(apiResources); 35 | await context.SaveChangesAsync(); 36 | #endif 37 | if (!context.Clients.Any()) 38 | { 39 | foreach (var client in IdentityServerSeed.GetClients(clientUrls, secret)) 40 | { 41 | context.Clients.Add(client.ToEntity()); 42 | } 43 | await context.SaveChangesAsync(); 44 | } 45 | if (!context.IdentityResources.Any()) 46 | { 47 | foreach (var resource in IdentityServerSeed.GetResources()) 48 | { 49 | context.IdentityResources.Add(resource.ToEntity()); 50 | } 51 | await context.SaveChangesAsync(); 52 | } 53 | if (!context.ApiResources.Any()) 54 | { 55 | foreach (var api in IdentityServerSeed.GetApis()) 56 | { 57 | context.ApiResources.Add(api.ToEntity()); 58 | } 59 | 60 | await context.SaveChangesAsync(); 61 | } 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /Example/Identity.API/Init/IdentityUserDbContextSeed.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using JieDDDFramework.Data.EntityFramework.Migrate; 6 | using JieDDDFramework.Module.Identity.Data; 7 | using JieDDDFramework.Module.Identity.Models; 8 | using Microsoft.AspNetCore.Identity; 9 | 10 | namespace Identity.API.Init 11 | { 12 | public class IdentityUserDbContextSeed : IDbContextSeed 13 | { 14 | private readonly IPasswordHasher _passwordHasher = new PasswordHasher(); 15 | public async Task SeedAsync(IdentityUserDbContext context) 16 | { 17 | #if DEBUG 18 | var users = context.Users.ToList(); 19 | context.Users.RemoveRange(users); 20 | await context.SaveChangesAsync(); 21 | 22 | #endif 23 | if (!context.Users.Any()) 24 | { 25 | context.Users.AddRange(GetDefaultUser()); 26 | 27 | await context.SaveChangesAsync(); 28 | } 29 | } 30 | 31 | private IEnumerable GetDefaultUser() 32 | { 33 | var user = 34 | new ApplicationUser() 35 | { 36 | City = "CQ", 37 | Country = "CN", 38 | Email = "demouser@xx.com", 39 | NormalizedEmail = "demouser@xx.com".ToUpper(), 40 | Id = Guid.NewGuid().ToString(), 41 | Name = "DemoUser", 42 | PhoneNumber = "1234567890", 43 | UserName = "demouser@xx.com", 44 | NormalizedUserName = "demouser@xx.com".ToUpper(), 45 | State = "WA", 46 | SecurityStamp = Guid.NewGuid().ToString("D"), 47 | }; 48 | 49 | user.PasswordHash = _passwordHasher.HashPassword(user, "123456"); 50 | 51 | return new List() 52 | { 53 | user 54 | }; 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /Example/Identity.API/Migrations/PersistedGrantDbContexts/20181211095830_initial.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using IdentityServer4.EntityFramework.DbContexts; 4 | using Microsoft.EntityFrameworkCore; 5 | using Microsoft.EntityFrameworkCore.Infrastructure; 6 | using Microsoft.EntityFrameworkCore.Migrations; 7 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 8 | 9 | namespace Identity.API.Migrations.PersistedGrantDbContexts 10 | { 11 | [DbContext(typeof(PersistedGrantDbContext))] 12 | [Migration("20181211095830_initial")] 13 | partial class initial 14 | { 15 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 16 | { 17 | #pragma warning disable 612, 618 18 | modelBuilder 19 | .HasAnnotation("ProductVersion", "2.1.4-rtm-31024") 20 | .HasAnnotation("Relational:MaxIdentifierLength", 64); 21 | 22 | modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.DeviceFlowCodes", b => 23 | { 24 | b.Property("UserCode") 25 | .ValueGeneratedOnAdd() 26 | .HasMaxLength(200); 27 | 28 | b.Property("ClientId") 29 | .IsRequired() 30 | .HasMaxLength(200); 31 | 32 | b.Property("CreationTime"); 33 | 34 | b.Property("Data") 35 | .IsRequired() 36 | .HasMaxLength(50000); 37 | 38 | b.Property("DeviceCode") 39 | .IsRequired() 40 | .HasMaxLength(200); 41 | 42 | b.Property("Expiration") 43 | .IsRequired(); 44 | 45 | b.Property("SubjectId") 46 | .HasMaxLength(200); 47 | 48 | b.HasKey("UserCode"); 49 | 50 | b.HasIndex("DeviceCode") 51 | .IsUnique(); 52 | 53 | b.HasIndex("UserCode") 54 | .IsUnique(); 55 | 56 | b.ToTable("DeviceCodes"); 57 | }); 58 | 59 | modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.PersistedGrant", b => 60 | { 61 | b.Property("Key") 62 | .HasMaxLength(200); 63 | 64 | b.Property("ClientId") 65 | .IsRequired() 66 | .HasMaxLength(200); 67 | 68 | b.Property("CreationTime"); 69 | 70 | b.Property("Data") 71 | .IsRequired() 72 | .HasMaxLength(50000); 73 | 74 | b.Property("Expiration"); 75 | 76 | b.Property("SubjectId") 77 | .HasMaxLength(200); 78 | 79 | b.Property("Type") 80 | .IsRequired() 81 | .HasMaxLength(50); 82 | 83 | b.HasKey("Key"); 84 | 85 | b.HasIndex("SubjectId", "ClientId", "Type"); 86 | 87 | b.ToTable("PersistedGrants"); 88 | }); 89 | #pragma warning restore 612, 618 90 | } 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /Example/Identity.API/Migrations/PersistedGrantDbContexts/20181211095830_initial.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.EntityFrameworkCore.Migrations; 3 | 4 | namespace Identity.API.Migrations.PersistedGrantDbContexts 5 | { 6 | public partial class initial : Migration 7 | { 8 | protected override void Up(MigrationBuilder migrationBuilder) 9 | { 10 | migrationBuilder.CreateTable( 11 | name: "DeviceCodes", 12 | columns: table => new 13 | { 14 | DeviceCode = table.Column(maxLength: 200, nullable: false), 15 | UserCode = table.Column(maxLength: 200, nullable: false), 16 | SubjectId = table.Column(maxLength: 200, nullable: true), 17 | ClientId = table.Column(maxLength: 200, nullable: false), 18 | CreationTime = table.Column(nullable: false), 19 | Expiration = table.Column(nullable: false), 20 | Data = table.Column(maxLength: 50000, nullable: false) 21 | }, 22 | constraints: table => 23 | { 24 | table.PrimaryKey("PK_DeviceCodes", x => x.UserCode); 25 | }); 26 | 27 | migrationBuilder.CreateTable( 28 | name: "PersistedGrants", 29 | columns: table => new 30 | { 31 | Key = table.Column(maxLength: 200, nullable: false), 32 | Type = table.Column(maxLength: 50, nullable: false), 33 | SubjectId = table.Column(maxLength: 200, nullable: true), 34 | ClientId = table.Column(maxLength: 200, nullable: false), 35 | CreationTime = table.Column(nullable: false), 36 | Expiration = table.Column(nullable: true), 37 | Data = table.Column(maxLength: 50000, nullable: false) 38 | }, 39 | constraints: table => 40 | { 41 | table.PrimaryKey("PK_PersistedGrants", x => x.Key); 42 | }); 43 | 44 | migrationBuilder.CreateIndex( 45 | name: "IX_DeviceCodes_DeviceCode", 46 | table: "DeviceCodes", 47 | column: "DeviceCode", 48 | unique: true); 49 | 50 | migrationBuilder.CreateIndex( 51 | name: "IX_DeviceCodes_UserCode", 52 | table: "DeviceCodes", 53 | column: "UserCode", 54 | unique: true); 55 | 56 | migrationBuilder.CreateIndex( 57 | name: "IX_PersistedGrants_SubjectId_ClientId_Type", 58 | table: "PersistedGrants", 59 | columns: new[] { "SubjectId", "ClientId", "Type" }); 60 | } 61 | 62 | protected override void Down(MigrationBuilder migrationBuilder) 63 | { 64 | migrationBuilder.DropTable( 65 | name: "DeviceCodes"); 66 | 67 | migrationBuilder.DropTable( 68 | name: "PersistedGrants"); 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /Example/Identity.API/Migrations/PersistedGrantDbContexts/PersistedGrantDbContextModelSnapshot.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using IdentityServer4.EntityFramework.DbContexts; 4 | using Microsoft.EntityFrameworkCore; 5 | using Microsoft.EntityFrameworkCore.Infrastructure; 6 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 7 | 8 | namespace Identity.API.Migrations.PersistedGrantDbContexts 9 | { 10 | [DbContext(typeof(PersistedGrantDbContext))] 11 | partial class PersistedGrantDbContextModelSnapshot : ModelSnapshot 12 | { 13 | protected override void BuildModel(ModelBuilder modelBuilder) 14 | { 15 | #pragma warning disable 612, 618 16 | modelBuilder 17 | .HasAnnotation("ProductVersion", "2.1.4-rtm-31024") 18 | .HasAnnotation("Relational:MaxIdentifierLength", 64); 19 | 20 | modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.DeviceFlowCodes", b => 21 | { 22 | b.Property("UserCode") 23 | .ValueGeneratedOnAdd() 24 | .HasMaxLength(200); 25 | 26 | b.Property("ClientId") 27 | .IsRequired() 28 | .HasMaxLength(200); 29 | 30 | b.Property("CreationTime"); 31 | 32 | b.Property("Data") 33 | .IsRequired() 34 | .HasMaxLength(50000); 35 | 36 | b.Property("DeviceCode") 37 | .IsRequired() 38 | .HasMaxLength(200); 39 | 40 | b.Property("Expiration") 41 | .IsRequired(); 42 | 43 | b.Property("SubjectId") 44 | .HasMaxLength(200); 45 | 46 | b.HasKey("UserCode"); 47 | 48 | b.HasIndex("DeviceCode") 49 | .IsUnique(); 50 | 51 | b.HasIndex("UserCode") 52 | .IsUnique(); 53 | 54 | b.ToTable("DeviceCodes"); 55 | }); 56 | 57 | modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.PersistedGrant", b => 58 | { 59 | b.Property("Key") 60 | .HasMaxLength(200); 61 | 62 | b.Property("ClientId") 63 | .IsRequired() 64 | .HasMaxLength(200); 65 | 66 | b.Property("CreationTime"); 67 | 68 | b.Property("Data") 69 | .IsRequired() 70 | .HasMaxLength(50000); 71 | 72 | b.Property("Expiration"); 73 | 74 | b.Property("SubjectId") 75 | .HasMaxLength(200); 76 | 77 | b.Property("Type") 78 | .IsRequired() 79 | .HasMaxLength(50); 80 | 81 | b.HasKey("Key"); 82 | 83 | b.HasIndex("SubjectId", "ClientId", "Type"); 84 | 85 | b.ToTable("PersistedGrants"); 86 | }); 87 | #pragma warning restore 612, 618 88 | } 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /Example/Identity.API/Models/LoginViewModel.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel.DataAnnotations; 4 | using System.Linq; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | using FluentValidation; 8 | using FluentValidation.Results; 9 | 10 | namespace Identity.API.Models 11 | { 12 | public class LoginViewModel 13 | { 14 | public string Email { get; set; } 15 | 16 | public string Password { get; set; } 17 | 18 | public bool RememberMe { get; set; } 19 | public string ReturnUrl { get; set; } 20 | } 21 | 22 | public class LoginViewModelValidator : AbstractValidator 23 | { 24 | public LoginViewModelValidator() 25 | { 26 | RuleFor(x => x.Email).NotEmpty().WithMessage("地址不能为空") 27 | .EmailAddress().WithMessage("请输入正确Email地址").WithErrorCode("-123"); 28 | 29 | RuleFor(x => x.Password).NotEmpty().WithMessage("密码不能为空"); 30 | When(x=>!string.IsNullOrEmpty(x.ReturnUrl), () => 31 | { 32 | RuleFor(x=>x.ReturnUrl).Must(x => x.StartsWith("http://") || x.StartsWith("https://")) 33 | .WithMessage("return url无效"); 34 | }); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Example/Identity.API/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | using IdentityServer4.EntityFramework.DbContexts; 7 | using JieDDDFramework.Data.EntityFramework.Migrate; 8 | using JieDDDFramework.Module.Identity.Data; 9 | using Microsoft.AspNetCore; 10 | using Microsoft.AspNetCore.Hosting; 11 | using Microsoft.Extensions.Configuration; 12 | using Microsoft.Extensions.Logging; 13 | 14 | namespace Identity.API 15 | { 16 | public class Program 17 | { 18 | public static void Main(string[] args) 19 | { 20 | var webHost = CreateWebHostBuilder(args).Build(); 21 | webHost.Services 22 | .MigrateDbContext() 23 | .MigrateDbContext() 24 | .MigrateDbContext(); 25 | webHost.Run(); 26 | } 27 | 28 | public static IWebHostBuilder CreateWebHostBuilder(string[] args) => 29 | WebHost.CreateDefaultBuilder(args) 30 | .UseKestrel() 31 | .UseContentRoot(Directory.GetCurrentDirectory()) 32 | .UseIISIntegration() 33 | .UseStartup() 34 | .ConfigureLogging((hostingContext, builder) => 35 | { 36 | builder.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); 37 | builder.AddConsole(); 38 | builder.AddDebug(); 39 | }); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Example/Identity.API/Properties/PublishProfiles/FolderProfile.pubxml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | FileSystem 9 | FileSystem 10 | Release 11 | Any CPU 12 | 13 | True 14 | False 15 | b640dcdb-6470-4b01-8a56-1d8c83ae1707 16 | bin\Debug\netcoreapp2.2\publish\ 17 | False 18 | 19 | -------------------------------------------------------------------------------- /Example/Identity.API/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "iisSettings": { 3 | "windowsAuthentication": false, 4 | "anonymousAuthentication": true, 5 | "iisExpress": { 6 | "applicationUrl": "http://localhost:53078", 7 | "sslPort": 0 8 | } 9 | }, 10 | "$schema": "http://json.schemastore.org/launchsettings.json", 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchBrowser": true, 15 | "launchUrl": "api/values", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | } 19 | }, 20 | "Identity.API": { 21 | "commandName": "Project", 22 | "launchBrowser": true, 23 | "environmentVariables": { 24 | "ASPNETCORE_ENVIRONMENT": "Development" 25 | }, 26 | "applicationUrl": "http://localhost:5000" 27 | }, 28 | "Docker": { 29 | "commandName": "Docker", 30 | "launchBrowser": true, 31 | "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/api/values" 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /Example/Identity.API/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Debug", 5 | "System": "Information", 6 | "Microsoft": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Example/Identity.API/appsettings.Production.json: -------------------------------------------------------------------------------- 1 | { 2 | "ConnectionStrings": { 3 | "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;MultipleActiveResultSets=true" 4 | } 5 | } -------------------------------------------------------------------------------- /Example/Identity.API/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "ConnectionString": "Server=192.168.199.237;Database=IdentityDb;Uid=root;Pwd=123456;", 3 | "Logging": { 4 | "LogLevel": { 5 | "Default": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*", 9 | "RedisConnectionString": "192.168.199.237", 10 | "MvcClient": "http://localhost:8989", 11 | "OrderClient": "http://localhost:8990", 12 | "IdentityClient": "http://localhost:5000", 13 | "Certificates": { 14 | "CerPath": "cas.clientservice.pfx", 15 | "Password": "123456" 16 | }, 17 | "JwtSettings": { 18 | "Audience": "identityserver", 19 | "Issuer": "http://localhost:5000", 20 | "SecretKey": "SecretKey", 21 | "ClientId": "identityswaggerui" 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Example/Identity.API/cas.clientservice.cer: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIDyTCCArGgAwIBAgIUfckulsdQN+nYTETsNtUAnkoxc4QwDQYJKoZIhvcNAQEL 3 | BQAwdDELMAkGA1UEBhMCQVUxDzANBgNVBAgMBmZlaWppZTESMBAGA1UEBwwJY2hv 4 | bmdxaW5nMQ8wDQYDVQQKDAZmZWlqaWUxDzANBgNVBAMMBmZlaWppZTEeMBwGCSqG 5 | SIb3DQEJARYPZmVpamllODlAcXEuY29tMB4XDTE4MTIzMTA3MjkwOVoXDTE5MTIz 6 | MTA3MjkwOVowdDELMAkGA1UEBhMCQVUxDzANBgNVBAgMBmZlaWppZTESMBAGA1UE 7 | BwwJY2hvbmdxaW5nMQ8wDQYDVQQKDAZmZWlqaWUxDzANBgNVBAMMBmZlaWppZTEe 8 | MBwGCSqGSIb3DQEJARYPZmVpamllODlAcXEuY29tMIIBIjANBgkqhkiG9w0BAQEF 9 | AAOCAQ8AMIIBCgKCAQEAwbvPsAQYZ9OP2WZ+ovm9RHrzBlfhHSpQaI43fJyyMrrn 10 | QR6bzK2c7ykMrQbityi83R1qvzJ0AeFCY0+sRYA9GE6le1Kn63ft5iakFWVam/P2 11 | 2WAAkhC/i/m3JGJ0LAewU5jlc/wa+8gz9LvoLtRX8sQOS3JiaHgbPucb54qEaILn 12 | 4OZeE7TLFspJHb1t670WZ/wItj63UyTVGocHc2ebDLudVjSFZSmTkahyCwTKjIiY 13 | OzzTr9K/4+hGjZH7EZt+k9BeDQLCfoZt7Wt95FOw++oTAvIR/3c+dTIw5GqAa4Rc 14 | hDy0IRBZDx9hVqy4DQ/T/CZyH8Hlc8MGwUQrQjLwbQIDAQABo1MwUTAdBgNVHQ4E 15 | FgQUGDc8rBw/YFeujJ/pRyvqQAhqAYwwHwYDVR0jBBgwFoAUGDc8rBw/YFeujJ/p 16 | RyvqQAhqAYwwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAEJdi 17 | nxdm/GlFp2bk1oqzkMOoa09V5fMGMs0vXNf7y66TtW3+KXUviZMyL559FtMpbExs 18 | STqr6GsYiqCQKRe38IJrzwA8wAED0+34TjqtzIbp5n4jhWQPN5V5MjSO6ceJwdSi 19 | gae9hk0+E3M3W5uRd18htX8YNIsHIQH6uXkR/S+kbFvXe2FgkdMcLEoun0u7Le1V 20 | Ti5ETOhabn1Y6EoTebGV+TQGMpb+zphxlBl7PxIYXVmt12Opq2PR0aIQdysqACiL 21 | SbQCm+0KsPePXZyz/c7ozsGJn8YldwTilmaYj+VpVV3N6l18OoSyZBPxcMANmYVg 22 | 6qEJbPNBl5RjnC1IzQ== 23 | -----END CERTIFICATE----- 24 | -------------------------------------------------------------------------------- /Example/Identity.API/cas.clientservice.key: -------------------------------------------------------------------------------- 1 | -----BEGIN PRIVATE KEY----- 2 | MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDBu8+wBBhn04/Z 3 | Zn6i+b1EevMGV+EdKlBojjd8nLIyuudBHpvMrZzvKQytBuK3KLzdHWq/MnQB4UJj 4 | T6xFgD0YTqV7Uqfrd+3mJqQVZVqb8/bZYACSEL+L+bckYnQsB7BTmOVz/Br7yDP0 5 | u+gu1FfyxA5LcmJoeBs+5xvnioRogufg5l4TtMsWykkdvW3rvRZn/Ai2PrdTJNUa 6 | hwdzZ5sMu51WNIVlKZORqHILBMqMiJg7PNOv0r/j6EaNkfsRm36T0F4NAsJ+hm3t 7 | a33kU7D76hMC8hH/dz51MjDkaoBrhFyEPLQhEFkPH2FWrLgND9P8JnIfweVzwwbB 8 | RCtCMvBtAgMBAAECggEAE4ZnJxkykHw8+i8fQjOjRJyTk6cVtAfItNDofLGaMAyw 9 | M9ru3tD8iQn9Eg8omEcNyccmNADUuj/GnhWwigyjm6iJewVYkR20J0brsJBXcnJD 10 | BaNsS0xO0b+oGo2loa5gsfwt2+OjoI6L1fV+MAIMnxXtTuNHUboRHOTT5iEKuTGT 11 | VBFTho+AMAgxJlKgmKuvTabG0y7aOlEGTFx9Qo63JN2GUBfrAqKgyF/zCb9xu/5V 12 | suyM6BaCUmTyI983xJTDhzn1ReAMyopVTDmwuDuq5L5jNk/rAAmOKoBxK9IvNIFJ 13 | Lwlaj78gxSjFGphIVjhK/ZVr57zH2V9rQcDnIwfPAQKBgQDqe8zyaz7mf73I2tcp 14 | JrF5Fg73sQN7VkE2v23hIW4hGq3srWelS9udTpn1U/reg2metepdBD175XcVAhmF 15 | a2Kc7bgPqFVaqNo3LOeon1qaJ9e5EZoyfCK1t8TEDd1lHPwJPHYxYihm+XzzZM7u 16 | zBC82w3rxf2D8aMgJU8o0f7QQQKBgQDTgsNQm+bYUlqhkt3wTaiCkEkPjJawQcDU 17 | D2k9TVz7JNcIngQ38WW0aT5+MxYI5M00xcSTP9F6/vlyoJ5rCYonYDHKO7J1B0de 18 | 2G3vyIEgbLEboXT3+KtiU/sPut0kWXtuSFYCpRras7WkvDWng7bWGObbL9ey20JB 19 | VhG73JMVLQKBgQDQy15quq6u5y6ijKOsxASiMs8vJdNY3yyAyKLaJj9/gNdAegRh 20 | vxOWlqgnORmZS+Ef7xL6sszg5ypLbaw2DrIn1NHiN12Rteth2D2L/CHcRQAljpQE 21 | wl7R+wpeHY53/AA9ZTZFsQcS8rOds7VEFDgPQuu5d3rQI7nC5RYA3kUNQQKBgQC6 22 | nxj4aeaAHgHrqCt9GPhC404jkxduQ0YBlet0dGtDCNlWuB3ewnbLfUTvkuGxTTgm 23 | hQ0SI3AQxyKP2lqM9OjaH00vNAccrSRy8iHmPRJ56o1GZOpQ1S9a3eCam3T92ppG 24 | zzpcsRMFvyTZSltJB7VuKKCg6xC1tjI6ddfF2zRHrQKBgQCtFTzt1u0Kq5MXKwSE 25 | k6yu4BbZOiwhp0zdB0W+zAjjm//TGG27k9GM/I8p9kDb7XxE72hn08HClIejdZmE 26 | 30C213UB8tTZEKTHsQCgYBFQb48tgd383GGtNxf+7x6tw84npwO/eh8BwMp4LoFH 27 | HHybSsHXaG3ICqvmdXYGFQWSOQ== 28 | -----END PRIVATE KEY----- 29 | -------------------------------------------------------------------------------- /Example/Identity.API/cas.clientservice.pfx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/feijie999/JieDDDFramework/4d1df0089196c681b3ca78fe7d15442fb5976884/Example/Identity.API/cas.clientservice.pfx -------------------------------------------------------------------------------- /Example/Order.API/Appsettings.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using JieDDDFramework.Core.Configures; 6 | 7 | namespace Order.API 8 | { 9 | public class AppSettings : BaseConfig 10 | { 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Example/Order.API/Controllers/AccountController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Identity.API.Models; 6 | using IdentityModel.Client; 7 | using JieDDDFramework.Module.Identity; 8 | using JieDDDFramework.Web; 9 | using JieDDDFramework.Web.ModelValidate; 10 | using Microsoft.AspNetCore.Mvc; 11 | using Microsoft.Extensions.Options; 12 | 13 | namespace Order.API.Controllers 14 | { 15 | [ApiController] 16 | [Route("api/[controller]")] 17 | public class AccountController : BaseController 18 | { 19 | private readonly JwtSettings _jwtSettings; 20 | 21 | public AccountController(IOptions jwtSettings) 22 | { 23 | _jwtSettings = jwtSettings.Value; 24 | } 25 | 26 | /// 27 | /// 登录 28 | /// 29 | /// 30 | /// { 31 | /// "email": "demouser@xx.com", 32 | /// "password": "123456" 33 | ///} 34 | /// 35 | /// 36 | /// 37 | [HttpPost] 38 | [Route("login")] 39 | public async Task Login([FromBody, Validator] LoginViewModel model) 40 | { 41 | var discoveryResponse = await DiscoveryClient.GetAsync(_jwtSettings.Issuer); 42 | var tokenClient = new TokenClient(discoveryResponse.TokenEndpoint, _jwtSettings.ClientId, _jwtSettings.SecretKey); 43 | var tokenResponse = await tokenClient.RequestResourceOwnerPasswordAsync(model.Email, model.Password); 44 | return Success(new { tokenResponse.IsError,tokenResponse.AccessToken}); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Example/Order.API/Controllers/OrderController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using IdentityServer4.Extensions; 6 | using JieDDDFramework.Data.EntityFramework; 7 | using JieDDDFramework.Data.Repository; 8 | using JieDDDFramework.Web; 9 | using JieDDDFramework.Web.Models; 10 | using JieDDDFramework.Web.ModelValidate; 11 | using MediatR; 12 | using Microsoft.AspNetCore.Authorization; 13 | using Microsoft.AspNetCore.Mvc; 14 | using Microsoft.AspNetCore.Mvc.ApiExplorer; 15 | using Microsoft.EntityFrameworkCore; 16 | using Order.Domain.Application.Commands; 17 | 18 | namespace Order.API.Controllers 19 | { 20 | [Route("api/[controller]")] 21 | [Authorize] 22 | [ApiController] 23 | public class OrderController : BaseController 24 | { 25 | private readonly IMediator _mediator; 26 | private readonly IRepositoryBase _repositoryBase; 27 | 28 | public OrderController(IMediator mediator, IRepositoryBase repositoryBase) 29 | { 30 | _mediator = mediator; 31 | _repositoryBase = repositoryBase; 32 | } 33 | 34 | /// 35 | /// 创建订单 36 | /// 37 | /// 38 | /// 39 | [HttpPost,Route("create")] 40 | public async Task CreateOrder([FromBody]CreateOrderCommand command) 41 | { 42 | command.UserId = User.GetSubjectId(); 43 | command.UserName = User.GetName(); 44 | var result = await _mediator.Send(command); 45 | return result?Success():Fail(); 46 | } 47 | 48 | /// 49 | /// 订单列表 50 | /// 51 | /// 52 | /// 53 | [HttpGet,Route("")] 54 | public async Task Orders([FromQuery, Validator] PagedCriteria criteria) 55 | { 56 | //在正式项目中不建议暴露领域对象,建议加入Application层,用于协调WebApi与领域对象 57 | var result = await _repositoryBase.Tables() 58 | .OrderByCreatedTime() 59 | .Select(x => new //在正式项目中应创建DTO对象来进行映射,可使用automapper组件 60 | { 61 | OrderId = x.Id, 62 | PaymentType = x.PaymentMethod.PaymentType.Name, 63 | x.CreatedTime, 64 | x.Address, 65 | Buyer = x.Buyer.Name, 66 | Item = x.OrderItems.Select(o => new {o.ProductId, o.ProductName, o.ProductCount, o.ProductPrice}) 67 | }) 68 | .ToPageResult(criteria.PageIndex, criteria.PageSize); 69 | return Success(result); 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /Example/Order.API/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM microsoft/dotnet:2.2-aspnetcore-runtime AS base 2 | WORKDIR /app 3 | EXPOSE 80 4 | EXPOSE 443 5 | 6 | FROM microsoft/dotnet:2.2-sdk AS build 7 | WORKDIR /src 8 | COPY ["Order.API/Order.API.csproj", "Order.API/"] 9 | RUN dotnet restore "Order.API/Order.API.csproj" 10 | COPY . . 11 | WORKDIR "/src/Order.API" 12 | RUN dotnet build "Order.API.csproj" -c Release -o /app 13 | 14 | FROM build AS publish 15 | RUN dotnet publish "Order.API.csproj" -c Release -o /app 16 | 17 | FROM base AS final 18 | WORKDIR /app 19 | COPY --from=publish /app . 20 | ENTRYPOINT ["dotnet", "Order.API.dll"] -------------------------------------------------------------------------------- /Example/Order.API/Models/LoginViewModel.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel.DataAnnotations; 4 | using System.Linq; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | using FluentValidation; 8 | using FluentValidation.Results; 9 | 10 | namespace Identity.API.Models 11 | { 12 | public class LoginViewModel 13 | { 14 | public string Email { get; set; } 15 | 16 | public string Password { get; set; } 17 | } 18 | 19 | public class LoginViewModelValidator : AbstractValidator 20 | { 21 | public LoginViewModelValidator() 22 | { 23 | RuleFor(x => x.Email).NotEmpty().WithMessage("地址不能为空") 24 | .EmailAddress().WithMessage("请输入正确Email地址").WithErrorCode("-123"); 25 | 26 | RuleFor(x => x.Password).NotEmpty().WithMessage("密码不能为空"); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Example/Order.API/Models/OrderAddedViewModel.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using FluentValidation; 6 | 7 | namespace Order.API.Models 8 | { 9 | public class OrderAddedViewModel 10 | { 11 | public string ProductId { get; set; } 12 | public int Count { get; set; } 13 | } 14 | 15 | public class OrderAddedViewModelValidator : AbstractValidator 16 | { 17 | public OrderAddedViewModelValidator() 18 | { 19 | RuleFor(x => x.ProductId).NotEmpty().WithMessage("ProductId无效"); 20 | RuleFor(x => x.Count).LessThan(1).WithMessage("Count无效"); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Example/Order.API/Order.API.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netcoreapp2.2 5 | aspnet-Order.API-928D113E-BE2C-4182-B287-EBE36172665A 6 | InProcess 7 | Linux 8 | 9 | 10 | 11 | C:\Users\feiji\source\repos\JieDDDFramework\Example\Order.API\Order.API.xml 12 | 1701;1702;1591; 13 | 0 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | PreserveNewest 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /Example/Order.API/Order.API.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Order.API 5 | 6 | 7 | 8 | 9 | 登录 10 | 11 | 12 | { 13 | "email": "demouser@xx.com", 14 | "password": "123456" 15 | } 16 | 17 | 18 | 19 | 20 | 21 | 22 | 创建订单 23 | 24 | 25 | 26 | 27 | 28 | 29 | 订单列表 30 | 31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /Example/Order.API/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | using JieDDDFramework.Data.EntityFramework.Migrate; 7 | using Microsoft.AspNetCore; 8 | using Microsoft.AspNetCore.Hosting; 9 | using Microsoft.Extensions.Configuration; 10 | using Microsoft.Extensions.Logging; 11 | using Order.Domain.DbContexts; 12 | 13 | namespace Order.API 14 | { 15 | public class Program 16 | { 17 | public static void Main(string[] args) 18 | { 19 | var webHost = CreateWebHostBuilder(args).Build(); 20 | webHost.Services.MigrateDbContext(); 21 | webHost.Run(); 22 | } 23 | 24 | public static IWebHostBuilder CreateWebHostBuilder(string[] args) => 25 | WebHost.CreateDefaultBuilder(args) 26 | .UseKestrel() 27 | .UseContentRoot(Directory.GetCurrentDirectory()) 28 | .UseUrls("http://localhost:8990") 29 | .UseStartup(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Example/Order.API/Properties/PublishProfiles/FolderProfile.pubxml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | FileSystem 9 | FileSystem 10 | Release 11 | Any CPU 12 | 13 | True 14 | False 15 | 482c46c6-d8e8-44f3-9104-92d7d2f87ae1 16 | bin\Release\netcoreapp2.2\publish\ 17 | False 18 | 19 | -------------------------------------------------------------------------------- /Example/Order.API/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "iisSettings": { 3 | "windowsAuthentication": false, 4 | "anonymousAuthentication": true, 5 | "iisExpress": { 6 | "applicationUrl": "http://localhost:63831", 7 | "sslPort": 44362 8 | } 9 | }, 10 | "$schema": "http://json.schemastore.org/launchsettings.json", 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchBrowser": true, 15 | "launchUrl": "api/values", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | } 19 | }, 20 | "Order.API": { 21 | "commandName": "Project", 22 | "launchBrowser": true, 23 | "launchUrl": "swagger", 24 | "environmentVariables": { 25 | "ASPNETCORE_ENVIRONMENT": "Development" 26 | }, 27 | "applicationUrl": "http://localhost:8990" 28 | }, 29 | "Docker": { 30 | "commandName": "Docker", 31 | "launchBrowser": true, 32 | "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/api/values" 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /Example/Order.API/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Debug", 5 | "System": "Information", 6 | "Microsoft": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Example/Order.API/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "ConnectionString": "Server=192.168.199.237;Database=OrderDb;Uid=root;Pwd=123456;", 3 | "Logging": { 4 | "LogLevel": { 5 | "Default": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*", 9 | "RedisConnectionString": "192.168.199.237", 10 | "MvcClient": "http://localhost:8989", 11 | "OrderClient": "http://localhost:8990", 12 | "IdentityClient": "http://localhost:5000", 13 | "JwtSettings": { 14 | "Audience": "order", 15 | "Issuer": "http://localhost:5000", 16 | "SecretKey": "SecretKey", 17 | "ClientId": "orderswaggerui" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Example/Order.Domain/Aggregates/BuyerAggregate/Buyer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using JieDDDFramework.Core.Domain; 5 | using JieDDDFramework.Core.Exceptions.Utilities; 6 | using Order.Domain.Events; 7 | 8 | namespace Order.Domain.Aggregates.BuyerAggregate 9 | { 10 | public class Buyer : Entity, IAggregateRoot 11 | { 12 | private readonly List _paymentMethods; 13 | public virtual IReadOnlyCollection PaymentMethods => _paymentMethods; 14 | 15 | private readonly List _orders; 16 | 17 | public virtual IReadOnlyCollection Orders => _orders; 18 | 19 | public string Name { get; private set; } 20 | 21 | public Buyer() 22 | { 23 | _orders = new List(); 24 | _paymentMethods = new List(); 25 | } 26 | 27 | public Buyer(string id, string name) : this() 28 | { 29 | base.Id = Check.NotEmpty(id, nameof(id)); 30 | Name = Check.NotEmpty(name, nameof(name)); 31 | } 32 | 33 | public void VerifyOrAddPaymentMethod(PaymentType paymentType, string freeCode,string orderId) 34 | { 35 | if (freeCode == "123456")//test 36 | { 37 | var payment = new PaymentMethod(freeCode,paymentType); 38 | AddDomainEvent(new BuyerAndPaymentMethodVerifiedDomainEvent(this, payment, orderId)); 39 | _paymentMethods.Add(payment); 40 | } 41 | else 42 | { 43 | //todo 44 | } 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Example/Order.Domain/Aggregates/BuyerAggregate/PaymentMethod.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using JieDDDFramework.Core.Domain; 5 | 6 | namespace Order.Domain.Aggregates.BuyerAggregate 7 | { 8 | public class PaymentMethod : Entity 9 | { 10 | public string FreeCode { get; private set; } 11 | 12 | public virtual PaymentType PaymentType { get; private set; } 13 | 14 | public PaymentMethod() { } 15 | public PaymentMethod(string freeCode, PaymentType paymentType) 16 | { 17 | FreeCode = freeCode; 18 | PaymentType = paymentType; 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Example/Order.Domain/Aggregates/BuyerAggregate/PaymentType.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using JieDDDFramework.Core.Domain; 5 | 6 | namespace Order.Domain.Aggregates.BuyerAggregate 7 | { 8 | public class PaymentType 9 | : Enumeration 10 | { 11 | public static PaymentType Alipay = new AlipayType(); 12 | public static PaymentType WeChat = new WeChatType(); 13 | 14 | public PaymentType(int id, string name) 15 | : base(id, name) 16 | { 17 | } 18 | 19 | private class AlipayType : PaymentType 20 | { 21 | public AlipayType() : base(1, "Alipay") 22 | { } 23 | } 24 | 25 | private class WeChatType : PaymentType 26 | { 27 | public WeChatType() : base(2, "WeChat") 28 | { } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Example/Order.Domain/Aggregates/OrderAggregate/Address.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using JieDDDFramework.Core.Domain; 5 | 6 | namespace Order.Domain.Aggregates.OrderAggregate 7 | { 8 | public class Address : ValueObject 9 | { 10 | public string Street { get; private set; } 11 | public string City { get; private set; } 12 | public string State { get; private set; } 13 | public string Country { get; private set; } 14 | public string ZipCode { get; private set; } 15 | private Address() { } 16 | public Address(string street, string city, string state, string country, string zipcode) 17 | { 18 | Street = street; 19 | City = city; 20 | State = state; 21 | Country = country; 22 | ZipCode = zipcode; 23 | } 24 | 25 | protected override IEnumerable GetAtomicValues() 26 | { 27 | yield return Street; 28 | yield return City; 29 | yield return State; 30 | yield return Country; 31 | yield return ZipCode; 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Example/Order.Domain/Aggregates/OrderAggregate/Order.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using JieDDDFramework.Core.Domain; 6 | using JieDDDFramework.Core.EntitySpecifications; 7 | using Order.Domain.Aggregates.BuyerAggregate; 8 | using Order.Domain.Events; 9 | 10 | namespace Order.Domain.Aggregates.OrderAggregate 11 | { 12 | public class Order : Entity, IAggregateRoot, ICreatedTimeState,IDeletedState 13 | { 14 | protected Order() 15 | { 16 | CreatedTime = DateTime.Now; 17 | _orderItems = new List(); 18 | } 19 | public Address Address { get; private set; } 20 | 21 | public int? OrderStatusId { get; private set; } 22 | public virtual OrderStatus OrderStatus { get; private set; } 23 | 24 | public string BuyerId { get; private set; } 25 | public virtual Buyer Buyer { get; private set; } 26 | 27 | public string PaymentMethodId { get; private set; } 28 | public virtual PaymentMethod PaymentMethod { get; private set; } 29 | public DateTime CreatedTime { get; private set; } 30 | public bool Deleted { get; private set; } 31 | public DateTime? DeletedTime { get; private set; } 32 | private List _orderItems; 33 | public virtual IReadOnlyCollection OrderItems => _orderItems; 34 | 35 | public Order(string userId, string userName, Address address,string buyerId = null, string paymentMethodId = null) : this() 36 | { 37 | BuyerId = buyerId; 38 | PaymentMethodId = paymentMethodId; 39 | OrderStatusId = OrderStatus.Submitted.Id; 40 | Address = address; 41 | 42 | var orderStartedDomainEvent = new OrderStartedDomainEvent(this, userId, userName); 43 | 44 | this.AddDomainEvent(orderStartedDomainEvent); 45 | } 46 | 47 | public void AddOrderItem(string productId, string productName, decimal unitPrice, decimal discount) 48 | { 49 | var existingOrderForProduct = _orderItems 50 | .SingleOrDefault(o => o.Id == productId); 51 | 52 | if (existingOrderForProduct != null) 53 | { 54 | 55 | if (discount > existingOrderForProduct.ProductCount) 56 | { 57 | existingOrderForProduct.SetNewDiscount(discount); 58 | } 59 | } 60 | else 61 | { 62 | 63 | var orderItem = new OrderItem(productId, productName, (int)discount, unitPrice); 64 | _orderItems.Add(orderItem); 65 | } 66 | } 67 | 68 | public void SetPaymentId(string id) 69 | { 70 | PaymentMethodId = id; 71 | } 72 | 73 | public void SetBuyerId(string id) 74 | { 75 | BuyerId = id; 76 | } 77 | 78 | 79 | public void Delete() 80 | { 81 | Deleted = true; 82 | DeletedTime = DateTime.Now; 83 | } 84 | 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /Example/Order.Domain/Aggregates/OrderAggregate/OrderItem.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using JieDDDFramework.Core.Domain; 5 | using JieDDDFramework.Core.Exceptions; 6 | 7 | namespace Order.Domain.Aggregates.OrderAggregate 8 | { 9 | public class OrderItem : Entity 10 | { 11 | public string ProductId { get; private set; } 12 | public string ProductName { get; private set; } 13 | public int ProductCount { get; private set; } 14 | public decimal ProductPrice { get; private set; } 15 | public string OrderId { get; private set; } 16 | public virtual Order Order { get; private set; } 17 | 18 | protected OrderItem() { } 19 | public OrderItem(string productId, string productName, int productCount, decimal productPrice) 20 | { 21 | ProductId = productId; 22 | ProductName = productName; 23 | ProductCount = productCount; 24 | ProductPrice = productPrice; 25 | } 26 | 27 | public void SetNewDiscount(decimal discount) 28 | { 29 | if (discount<0) 30 | { 31 | throw new DomainException("Discount is not valid"); 32 | } 33 | 34 | ProductCount = (int) discount; 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Example/Order.Domain/Aggregates/OrderAggregate/OrderStatus.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using JieDDDFramework.Core.Domain; 6 | using JieDDDFramework.Core.Exceptions; 7 | 8 | namespace Order.Domain.Aggregates.OrderAggregate 9 | { 10 | public class OrderStatus 11 | : Enumeration 12 | { 13 | public static OrderStatus Submitted = new OrderStatus(1, nameof(Submitted).ToLowerInvariant()); 14 | public static OrderStatus AwaitingValidation = new OrderStatus(2, nameof(AwaitingValidation).ToLowerInvariant()); 15 | public static OrderStatus StockConfirmed = new OrderStatus(3, nameof(StockConfirmed).ToLowerInvariant()); 16 | public static OrderStatus Paid = new OrderStatus(4, nameof(Paid).ToLowerInvariant()); 17 | public static OrderStatus Shipped = new OrderStatus(5, nameof(Shipped).ToLowerInvariant()); 18 | public static OrderStatus Cancelled = new OrderStatus(6, nameof(Cancelled).ToLowerInvariant()); 19 | 20 | protected OrderStatus() 21 | { 22 | } 23 | 24 | public OrderStatus(int id, string name) 25 | : base(id, name) 26 | { 27 | } 28 | 29 | public static IEnumerable List() => 30 | new[] { Submitted, AwaitingValidation, StockConfirmed, Paid, Shipped, Cancelled }; 31 | 32 | public static OrderStatus FromName(string name) 33 | { 34 | var state = List() 35 | .SingleOrDefault(s => string.Equals(s.Name, name, StringComparison.CurrentCultureIgnoreCase)); 36 | 37 | if (state == null) 38 | { 39 | throw new DomainException($"Possible values for OrderStatus: {string.Join(",", List().Select(s => s.Name))}"); 40 | } 41 | 42 | return state; 43 | } 44 | 45 | public static OrderStatus From(int id) 46 | { 47 | var state = List().SingleOrDefault(s => s.Id == id); 48 | 49 | if (state == null) 50 | { 51 | throw new DomainException($"Possible values for OrderStatus: {string.Join(",", List().Select(s => s.Name))}"); 52 | } 53 | 54 | return state; 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /Example/Order.Domain/Application/Commands/CreateOrderCommand.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Runtime.Serialization; 5 | using System.Text; 6 | using FluentValidation; 7 | using MediatR; 8 | 9 | namespace Order.Domain.Application.Commands 10 | { 11 | public class CreateOrderCommand 12 | : IRequest 13 | { 14 | public List OrderItems { get; set; } 15 | public string UserId { get; set; } 16 | public string UserName { get; set; } 17 | 18 | public string City { get; set; } 19 | public string Street { get; set; } 20 | 21 | public string State { get; set; } 22 | 23 | public string Country { get; set; } 24 | 25 | public string ZipCode { get; set; } 26 | 27 | public CreateOrderCommand() 28 | { 29 | OrderItems = new List(); 30 | } 31 | 32 | public CreateOrderCommand(List orderItem, string userId, string userName, string city, 33 | string street, string state, string country, string zipcode) 34 | { 35 | OrderItems = orderItem; 36 | UserId = userId; 37 | UserName = userName; 38 | City = city; 39 | Street = street; 40 | State = state; 41 | Country = country; 42 | ZipCode = zipcode; 43 | } 44 | 45 | 46 | public class OrderItemDTO 47 | { 48 | public string ProductId { get; set; } 49 | 50 | public string ProductName { get; set; } 51 | 52 | public decimal UnitPrice { get; set; } 53 | 54 | public decimal Discount { get; set; } 55 | 56 | public int Units { get; set; } 57 | 58 | public string PictureUrl { get; set; } 59 | } 60 | 61 | public class CreateOrderCommandValidator : AbstractValidator 62 | { 63 | public CreateOrderCommandValidator() 64 | { 65 | CascadeMode = CascadeMode.StopOnFirstFailure; 66 | RuleFor(command => command.City).NotEmpty().WithErrorCode("3001"); 67 | RuleFor(command => command.Street).NotEmpty().WithErrorCode("3002"); 68 | RuleFor(command => command.State).NotEmpty().WithErrorCode("3003"); 69 | RuleFor(command => command.Country).NotEmpty().WithErrorCode("3004"); 70 | RuleFor(command => command.ZipCode).NotEmpty().WithErrorCode("3005"); 71 | RuleFor(command => command.OrderItems).Must(x => x.Any()) 72 | .WithMessage("订单项不能为空").WithErrorCode("3006"); 73 | } 74 | } 75 | 76 | public class OrderItemValidator : AbstractValidator 77 | { 78 | public OrderItemValidator() 79 | { 80 | CascadeMode = CascadeMode.StopOnFirstFailure; 81 | RuleFor(x => x.Discount).GreaterThan(0).WithMessage("数量不能小于1").WithErrorCode("31001"); 82 | RuleFor(x => x.UnitPrice).GreaterThan(0).WithMessage("数量不能为空价格不能小于0").WithErrorCode("3102"); 83 | } 84 | } 85 | } 86 | 87 | } 88 | -------------------------------------------------------------------------------- /Example/Order.Domain/Application/Commands/CreateOrderCommandHandler.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | using JieDDDFramework.Data.Repository; 7 | using MediatR; 8 | using Order.Domain.Aggregates.OrderAggregate; 9 | 10 | namespace Order.Domain.Application.Commands 11 | { 12 | public class CreateOrderCommandHandler 13 | : IRequestHandler 14 | { 15 | private readonly IRepositoryBase _orderRepository; 16 | private readonly IMediator _mediator; 17 | 18 | public CreateOrderCommandHandler(IMediator mediator, IRepositoryBase orderRepository) 19 | { 20 | _orderRepository = orderRepository ?? throw new ArgumentNullException(nameof(orderRepository)); 21 | _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator)); 22 | } 23 | 24 | public async Task Handle(CreateOrderCommand message, CancellationToken cancellationToken) 25 | { 26 | var address = new Address(message.Street, message.City, message.State, message.Country, message.ZipCode); 27 | var order = new Aggregates.OrderAggregate.Order(message.UserId, message.UserName, address); 28 | 29 | foreach (var item in message.OrderItems) 30 | { 31 | order.AddOrderItem(item.ProductId, item.ProductName, item.Discount, item.UnitPrice); 32 | } 33 | await _orderRepository.InsertAsync(order, cancellationToken); 34 | return await _orderRepository.UnitOfWork 35 | .SaveEntitiesAsync(cancellationToken); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Example/Order.Domain/DbContexts/OrderDbContext.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using JieDDDFramework.Core.Exceptions.Utilities; 5 | using JieDDDFramework.Data.EntityFramework.DbContext; 6 | using JieDDDFramework.Data.EntityFramework.ModelConfigurations; 7 | using MediatR; 8 | using Microsoft.EntityFrameworkCore; 9 | using Order.Domain.Aggregates.BuyerAggregate; 10 | using Order.Domain.Aggregates.OrderAggregate; 11 | 12 | namespace Order.Domain.DbContexts 13 | { 14 | public class OrderDbContext: DomainDbContext 15 | { 16 | public DbSet Orders { get; set; } 17 | public DbSet OrderItems { get; set; } 18 | public DbSet Payments { get; set; } 19 | public DbSet Buyers { get; set; } 20 | public DbSet PaymentTypes { get; set; } 21 | public DbSet OrderStatus { get; set; } 22 | 23 | private readonly IMediator _mediator; 24 | public OrderDbContext(DbContextOptions options, IMediator mediator, IModelConfigurationProvider modelConfigurationProvider) : base(options, mediator, modelConfigurationProvider) 25 | { 26 | Check.NotNull(mediator, nameof(mediator)); 27 | _mediator = mediator; 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Example/Order.Domain/DbContexts/OrderDbContextSeed.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | using JieDDDFramework.Core.Domain; 6 | using JieDDDFramework.Data.EntityFramework.Migrate; 7 | using Microsoft.EntityFrameworkCore.Internal; 8 | using Order.Domain.Aggregates.BuyerAggregate; 9 | using Order.Domain.Aggregates.OrderAggregate; 10 | 11 | namespace Order.Domain.DbContexts 12 | { 13 | public class OrderDbContextSeed : IDbContextSeed 14 | { 15 | public async Task SeedAsync(OrderDbContext context) 16 | { 17 | if (!context.OrderStatus.Any()) 18 | { 19 | await context.OrderStatus.AddRangeAsync(OrderStatus.List()); 20 | } 21 | if (!context.PaymentTypes.Any()) 22 | { 23 | await context.PaymentTypes.AddRangeAsync(Enumeration.GetAll()); 24 | } 25 | await context.SaveChangesAsync(); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Example/Order.Domain/EntityConfigurations/BuyerEntityTypeConfiguration.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using JieDDDFramework.Data.EntityFramework.ModelConfigurations; 5 | using Microsoft.EntityFrameworkCore; 6 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 7 | using Order.Domain.Aggregates.BuyerAggregate; 8 | 9 | namespace Order.Domain.EntityConfigurations 10 | { 11 | public class BuyerEntityTypeConfiguration 12 | : DDDEntityTypeConfiguration 13 | { 14 | public override void Map(EntityTypeBuilder buyerConfiguration) 15 | { 16 | buyerConfiguration.ToTable("buyers"); 17 | 18 | buyerConfiguration.HasKey(b => b.Id); 19 | 20 | buyerConfiguration.Property(b => b.Name).IsRequired().HasMaxLength(32); 21 | 22 | buyerConfiguration.HasMany(b => b.PaymentMethods) 23 | .WithOne() 24 | .HasForeignKey("BuyerId") 25 | .OnDelete(DeleteBehavior.Cascade); 26 | 27 | //var navigation = buyerConfiguration.Metadata.FindNavigation(nameof(Buyer.PaymentMethods)); 28 | //buyerConfiguration.Property(x => x.PaymentMethods); 29 | //navigation.SetPropertyAccessMode(PropertyAccessMode.FieldDuringConstruction); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Example/Order.Domain/EntityConfigurations/OrderEntityTypeConfiguration.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using JieDDDFramework.Data.EntityFramework.ModelConfigurations; 5 | using Microsoft.EntityFrameworkCore; 6 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 7 | using Order.Domain.Aggregates.BuyerAggregate; 8 | 9 | namespace Order.Domain.EntityConfigurations 10 | { 11 | public class OrderEntityTypeConfiguration : DDDEntityTypeConfiguration 12 | { 13 | public override void Map(EntityTypeBuilder orderConfiguration) 14 | { 15 | orderConfiguration.ToTable("orders"); 16 | 17 | orderConfiguration.HasKey(o => o.Id); 18 | 19 | orderConfiguration.OwnsOne(o => o.Address); 20 | orderConfiguration.Property(x => x.CreatedTime).IsRequired(); 21 | orderConfiguration.HasOne(x => x.Buyer) 22 | .WithMany(x => x.Orders) 23 | .HasForeignKey(x => x.BuyerId) 24 | .IsRequired(false) 25 | .OnDelete(DeleteBehavior.Restrict); 26 | 27 | orderConfiguration.HasOne(x => x.OrderStatus) 28 | .WithMany() 29 | .HasForeignKey(x => x.OrderStatusId); 30 | 31 | orderConfiguration.HasOne(x => x.PaymentMethod) 32 | .WithMany() 33 | .HasForeignKey(x => x.PaymentMethodId); 34 | 35 | orderConfiguration.HasMany(x => x.OrderItems) 36 | .WithOne(x => x.Order) 37 | .HasForeignKey(x => x.OrderId); 38 | 39 | //var navigation = orderConfiguration.Metadata.FindNavigation(nameof(Aggregates.OrderAggregate.Order.OrderItems)); 40 | 41 | //navigation.SetPropertyAccessMode(PropertyAccessMode.Field); 42 | 43 | //orderConfiguration.HasOne() 44 | // .WithMany() 45 | // .HasForeignKey("PaymentMethodId") 46 | // .IsRequired(false) 47 | // .OnDelete(DeleteBehavior.Restrict); 48 | 49 | //orderConfiguration.HasOne() 50 | // .WithMany() 51 | // .IsRequired(false) 52 | // .HasForeignKey("BuyerId"); 53 | 54 | //orderConfiguration.HasOne(o => o.OrderStatus) 55 | // .WithMany() 56 | // .HasForeignKey("OrderStatusId"); 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /Example/Order.Domain/EntityConfigurations/OrderItemEntityTypeConfiguration.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using JieDDDFramework.Data.EntityFramework.ModelConfigurations; 5 | using Microsoft.AspNetCore.Builder.Extensions; 6 | using Microsoft.EntityFrameworkCore; 7 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 8 | using Order.Domain.Aggregates.OrderAggregate; 9 | 10 | namespace Order.Domain.EntityConfigurations 11 | { 12 | public class OrderItemEntityTypeConfiguration : DDDEntityTypeConfiguration 13 | { 14 | public override void Map(EntityTypeBuilder configuration) 15 | { 16 | configuration.ToTable("orderItems"); 17 | configuration.Property(x => x.ProductId).IsRequired().HasMaxLength(32); 18 | configuration.Property(x => x.ProductName).IsRequired().HasMaxLength(32); 19 | 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Example/Order.Domain/EntityConfigurations/OrderStatusEntityTypeConfiguration.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using JieDDDFramework.Data.EntityFramework.ModelConfigurations; 5 | using Microsoft.EntityFrameworkCore; 6 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 7 | using Order.Domain.Aggregates.OrderAggregate; 8 | 9 | namespace Order.Domain.EntityConfigurations 10 | { 11 | public class OrderStatusEntityTypeConfiguration 12 | : IEntityTypeConfiguration 13 | { 14 | public void Configure(EntityTypeBuilder orderStatusConfiguration) 15 | { 16 | orderStatusConfiguration.ToTable("orderstatus"); 17 | 18 | orderStatusConfiguration.HasKey(o => o.Id); 19 | 20 | orderStatusConfiguration.Property(o => o.Id) 21 | .HasDefaultValue(1) 22 | .ValueGeneratedNever() 23 | .IsRequired(); 24 | 25 | orderStatusConfiguration.Property(o => o.Name) 26 | .HasMaxLength(200) 27 | .IsRequired(); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Example/Order.Domain/EntityConfigurations/PaymentMethodEntityTypeConfiguration.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using JieDDDFramework.Data.EntityFramework.ModelConfigurations; 5 | using Microsoft.EntityFrameworkCore; 6 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 7 | using Order.Domain.Aggregates.BuyerAggregate; 8 | 9 | namespace Order.Domain.EntityConfigurations 10 | { 11 | public class PaymentMethodEntityTypeConfiguration : DDDEntityTypeConfiguration 12 | { 13 | public override void Map(EntityTypeBuilder configuration) 14 | { 15 | configuration.ToTable("paymentmethods"); 16 | configuration.HasKey(x => x.Id); 17 | configuration.Property("BuyerId") 18 | .IsRequired(); 19 | configuration.Property(x => x.FreeCode).HasMaxLength(32); 20 | configuration.HasOne(x => x.PaymentType) 21 | .WithMany(); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Example/Order.Domain/EntityConfigurations/PaymentTypeEntityTypeConfiguration.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using JieDDDFramework.Data.EntityFramework.ModelConfigurations; 5 | using Microsoft.EntityFrameworkCore; 6 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 7 | using Order.Domain.Aggregates.BuyerAggregate; 8 | 9 | namespace Order.Domain.EntityConfigurations 10 | { 11 | public class PaymentTypeEntityTypeConfiguration : IEntityTypeConfiguration 12 | { 13 | public void Configure(EntityTypeBuilder builder) 14 | { 15 | builder.ToTable("paymenttypes"); 16 | builder.HasKey(x => x.Id); 17 | builder.Property(ct => ct.Id) 18 | .HasDefaultValue(1) 19 | .ValueGeneratedNever() 20 | .IsRequired(); 21 | 22 | builder.Property(ct => ct.Name) 23 | .HasMaxLength(32) 24 | .IsRequired(); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Example/Order.Domain/Events/BuyerAndPaymentMethodVerifiedDomainEvent.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using MediatR; 5 | using Order.Domain.Aggregates.BuyerAggregate; 6 | 7 | namespace Order.Domain.Events 8 | { 9 | public class BuyerAndPaymentMethodVerifiedDomainEvent 10 | : INotification 11 | { 12 | public Buyer Buyer { get; private set; } 13 | public PaymentMethod Payment { get; private set; } 14 | public string OrderId { get; private set; } 15 | 16 | public BuyerAndPaymentMethodVerifiedDomainEvent(Buyer buyer, PaymentMethod payment, string orderId) 17 | { 18 | Buyer = buyer; 19 | Payment = payment; 20 | OrderId = orderId; 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Example/Order.Domain/Events/DomainEventHandlers/OrderStartedDomainEventHandler.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | using JieDDDFramework.Core.Exceptions.Utilities; 7 | using JieDDDFramework.Data.Repository; 8 | using MediatR; 9 | using Microsoft.Extensions.Logging; 10 | using Order.Domain.Aggregates.BuyerAggregate; 11 | 12 | namespace Order.Domain.Events.DomainEventHandlers 13 | { 14 | public class OrderStartedDomainEventHandler : INotificationHandler 15 | { 16 | private readonly ILoggerFactory _logger; 17 | private readonly IRepositoryBase _buyerRepository; 18 | 19 | public OrderStartedDomainEventHandler(IRepositoryBase buyerRepository, ILoggerFactory logger) 20 | { 21 | _buyerRepository = Check.NotNull(buyerRepository, nameof(buyerRepository)); 22 | _logger = Check.NotNull(logger, nameof(logger)); ; 23 | } 24 | 25 | public async Task Handle(OrderStartedDomainEvent orderStartedEvent, CancellationToken cancellationToken) 26 | { 27 | var buyer = await _buyerRepository.FindEntityAsync(orderStartedEvent.UserId); 28 | var buyerOriginallyExisted = buyer != null; 29 | 30 | if (!buyerOriginallyExisted) 31 | { 32 | buyer = new Buyer(orderStartedEvent.UserId, orderStartedEvent.UserName); 33 | } 34 | 35 | buyer.VerifyOrAddPaymentMethod(null, 36 | "123456",orderStartedEvent.Order.Id); 37 | if (buyerOriginallyExisted) 38 | { 39 | _buyerRepository.Update(buyer); 40 | } 41 | else 42 | { 43 | await _buyerRepository.InsertAsync(buyer, cancellationToken); 44 | } 45 | await _buyerRepository.UnitOfWork 46 | .SaveEntitiesAsync(cancellationToken); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Example/Order.Domain/Events/DomainEventHandlers/UpdateOrderWhenBuyerAndPaymentMethodVerifiedDomainEventHandler.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | using JieDDDFramework.Core.Exceptions.Utilities; 7 | using JieDDDFramework.Data.Repository; 8 | using MediatR; 9 | using Microsoft.Extensions.Logging; 10 | 11 | namespace Order.Domain.Events.DomainEventHandlers 12 | { 13 | public class UpdateOrderWhenBuyerAndPaymentMethodVerifiedDomainEventHandler 14 | : INotificationHandler 15 | { 16 | private readonly IRepositoryBase _orderRepository; 17 | private readonly ILoggerFactory _logger; 18 | 19 | public UpdateOrderWhenBuyerAndPaymentMethodVerifiedDomainEventHandler( 20 | IRepositoryBase orderRepository, ILoggerFactory logger) 21 | { 22 | _orderRepository = Check.NotNull(orderRepository, nameof(orderRepository)); 23 | _logger = Check.NotNull(logger, nameof(logger)); 24 | } 25 | public async Task Handle(BuyerAndPaymentMethodVerifiedDomainEvent buyerPaymentMethodVerifiedEvent, CancellationToken cancellationToken) 26 | { 27 | var orderToUpdate = await _orderRepository.FindEntityAsync(buyerPaymentMethodVerifiedEvent.OrderId); 28 | orderToUpdate.SetBuyerId(buyerPaymentMethodVerifiedEvent.Buyer.Id); 29 | orderToUpdate.SetPaymentId(buyerPaymentMethodVerifiedEvent.Payment.Id); 30 | 31 | _logger.CreateLogger(nameof(UpdateOrderWhenBuyerAndPaymentMethodVerifiedDomainEventHandler)) 32 | .LogTrace($"Order with Id: {buyerPaymentMethodVerifiedEvent.OrderId} has been successfully updated with a payment method id: { buyerPaymentMethodVerifiedEvent.Payment.Id }"); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Example/Order.Domain/Events/OrderStartedDomainEvent.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using MediatR; 5 | 6 | namespace Order.Domain.Events 7 | { 8 | public class OrderStartedDomainEvent : INotification 9 | { 10 | public string UserId { get; } 11 | public string UserName { get; } 12 | public Aggregates.OrderAggregate.Order Order { get; } 13 | 14 | public OrderStartedDomainEvent(Aggregates.OrderAggregate.Order order, string userId, string userName) 15 | { 16 | Order = order; 17 | UserId = userId; 18 | UserName = userName; 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Example/Order.Domain/Order.Domain.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netstandard2.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /JieDDDFramework.Core/Configures/BaseConfig.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | namespace JieDDDFramework.Core.Configures 3 | { 4 | public class BaseConfig 5 | { 6 | public string ConnectionString { get; set; } 7 | public bool IsClusterEnv { get; set; } = false; 8 | 9 | public string RedisConnectionString { get; set; } 10 | public Logging Logging { get; set; } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /JieDDDFramework.Core/Configures/ConfigureExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.Extensions.Configuration; 3 | using Microsoft.Extensions.DependencyInjection; 4 | 5 | namespace JieDDDFramework.Core.Configures 6 | { 7 | public static class ConfigureExtensions 8 | { 9 | public static TOptions ConfigureOption(this IServiceCollection services,IConfiguration configuration,Func provider) where TOptions : class 10 | { 11 | if (services == null) throw new ArgumentNullException(nameof(services)); 12 | if (configuration == null) throw new ArgumentNullException(nameof(configuration)); 13 | if (provider == null) throw new ArgumentNullException(nameof(provider)); 14 | var config = provider(); 15 | configuration.Bind(config); 16 | services.AddOptions(); 17 | services.Configure(configuration); 18 | return config; 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /JieDDDFramework.Core/Configures/Connectionstrings.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | namespace JieDDDFramework.Core.Configures 3 | { 4 | public class Connectionstrings 5 | { 6 | public string DefaultConnection { get; set; } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /JieDDDFramework.Core/Configures/Logging.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | namespace JieDDDFramework.Core.Configures 3 | { 4 | public class Logging 5 | { 6 | public bool IncludeScopes { get; set; } 7 | public Loglevel LogLevel { get; set; } 8 | } 9 | 10 | public class Loglevel 11 | { 12 | public string Default { get; set; } 13 | public string System { get; set; } 14 | public string Microsoft { get; set; } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /JieDDDFramework.Core/Domain/Entity.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using MediatR; 5 | 6 | namespace JieDDDFramework.Core.Domain 7 | { 8 | public abstract class Entity : IEntity 9 | { 10 | protected int? RequestedHashCode; 11 | 12 | private List _domainEvents; 13 | public IReadOnlyCollection DomainEvents => _domainEvents?.AsReadOnly(); 14 | 15 | public void AddDomainEvent(INotification eventItem) 16 | { 17 | _domainEvents = _domainEvents ?? new List(); 18 | _domainEvents.Add(eventItem); 19 | } 20 | 21 | public void RemoveDomainEvent(INotification eventItem) 22 | { 23 | _domainEvents?.Remove(eventItem); 24 | } 25 | 26 | public void ClearDomainEvents() 27 | { 28 | _domainEvents.Clear(); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /JieDDDFramework.Core/Domain/Entity`1.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace JieDDDFramework.Core.Domain 6 | { 7 | public abstract class Entity : Entity where TKey :class 8 | { 9 | public virtual TKey Id { get; protected set; } 10 | 11 | public bool IsTransient() 12 | { 13 | return this.Id == default(TKey); 14 | } 15 | 16 | public override bool Equals(object obj) 17 | { 18 | if (!(obj is Entity)) 19 | return false; 20 | 21 | if (ReferenceEquals(this, obj)) 22 | return true; 23 | 24 | if (GetType() != obj.GetType()) 25 | return false; 26 | 27 | var item = (Entity)obj; 28 | 29 | if (item.IsTransient() || this.IsTransient()) 30 | return false; 31 | else 32 | return item.Id == this.Id; 33 | } 34 | 35 | public override int GetHashCode() 36 | { 37 | if (!IsTransient()) 38 | { 39 | if (!RequestedHashCode.HasValue) 40 | RequestedHashCode = Id.GetHashCode() ^ 31; // XOR for random distribution (http://blogs.msdn.com/b/ericlippert/archive/2011/02/28/guidelines-and-rules-for-gethashcode.aspx) 41 | 42 | return RequestedHashCode.Value; 43 | } 44 | else 45 | return base.GetHashCode(); 46 | 47 | } 48 | 49 | public static bool operator ==(Entity left, Entity right) 50 | { 51 | if (Equals(left, null)) 52 | return Equals(right, null); 53 | else 54 | return left.Equals(right); 55 | } 56 | 57 | public static bool operator !=(Entity left, Entity right) 58 | { 59 | return !(left == right); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /JieDDDFramework.Core/Domain/Enumeration.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Reflection; 5 | using System.Text; 6 | 7 | namespace JieDDDFramework.Core.Domain 8 | { 9 | public abstract class Enumeration : IComparable 10 | { 11 | public string Name { get; private set; } 12 | 13 | public int Id { get; private set; } 14 | 15 | protected Enumeration() 16 | { } 17 | 18 | protected Enumeration(int id, string name) 19 | { 20 | Id = id; 21 | Name = name; 22 | } 23 | 24 | public override string ToString() => Name; 25 | 26 | public static IEnumerable GetAll() where T : Enumeration 27 | { 28 | var fields = typeof(T).GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly); 29 | 30 | return fields.Select(f => f.GetValue(null)).Cast(); 31 | } 32 | 33 | public override bool Equals(object obj) 34 | { 35 | var otherValue = obj as Enumeration; 36 | 37 | if (otherValue == null) 38 | return false; 39 | 40 | var typeMatches = GetType().Equals(obj.GetType()); 41 | var valueMatches = Id.Equals(otherValue.Id); 42 | 43 | return typeMatches && valueMatches; 44 | } 45 | 46 | public override int GetHashCode() => Id.GetHashCode(); 47 | 48 | public static int AbsoluteDifference(Enumeration firstValue, Enumeration secondValue) 49 | { 50 | var absoluteDifference = Math.Abs(firstValue.Id - secondValue.Id); 51 | return absoluteDifference; 52 | } 53 | 54 | public static T FromValue(int value) where T : Enumeration 55 | { 56 | var matchingItem = Parse(value, "value", item => item.Id == value); 57 | return matchingItem; 58 | } 59 | 60 | public static T FromDisplayName(string displayName) where T : Enumeration 61 | { 62 | var matchingItem = Parse(displayName, "display name", item => item.Name == displayName); 63 | return matchingItem; 64 | } 65 | 66 | private static T Parse(K value, string description, Func predicate) where T : Enumeration 67 | { 68 | var matchingItem = GetAll().FirstOrDefault(predicate); 69 | 70 | if (matchingItem == null) 71 | throw new InvalidOperationException($"'{value}' is not a valid {description} in {typeof(T)}"); 72 | 73 | return matchingItem; 74 | } 75 | 76 | public int CompareTo(object other) => Id.CompareTo(((Enumeration)other).Id); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /JieDDDFramework.Core/Domain/IAggregateRoot.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace JieDDDFramework.Core.Domain 6 | { 7 | public interface IAggregateRoot : IEntity 8 | { 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /JieDDDFramework.Core/Domain/IEntity.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using MediatR; 5 | 6 | namespace JieDDDFramework.Core.Domain 7 | { 8 | public interface IEntity 9 | { 10 | IReadOnlyCollection DomainEvents { get; } 11 | void AddDomainEvent(INotification eventItem); 12 | 13 | void RemoveDomainEvent(INotification eventItem); 14 | 15 | void ClearDomainEvents(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /JieDDDFramework.Core/Domain/IRepository.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace JieDDDFramework.Core.Domain 6 | { 7 | public interface IRepository where T : IAggregateRoot 8 | { 9 | IUnitOfWork UnitOfWork { get; } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /JieDDDFramework.Core/Domain/IUnitOfWork.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | 7 | namespace JieDDDFramework.Core.Domain 8 | { 9 | public interface IUnitOfWork : IDisposable 10 | { 11 | Task SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken)); 12 | Task SaveEntitiesAsync(CancellationToken cancellationToken = default(CancellationToken)); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /JieDDDFramework.Core/Domain/ValueObject.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace JieDDDFramework.Core.Domain 7 | { 8 | public abstract class ValueObject 9 | { 10 | protected static bool EqualOperator(ValueObject left, ValueObject right) 11 | { 12 | if (ReferenceEquals(left, null) ^ ReferenceEquals(right, null)) 13 | { 14 | return false; 15 | } 16 | return ReferenceEquals(left, null) || left.Equals(right); 17 | } 18 | 19 | protected static bool NotEqualOperator(ValueObject left, ValueObject right) 20 | { 21 | return !(EqualOperator(left, right)); 22 | } 23 | 24 | protected abstract IEnumerable GetAtomicValues(); 25 | 26 | public override bool Equals(object obj) 27 | { 28 | if (obj == null || obj.GetType() != GetType()) 29 | { 30 | return false; 31 | } 32 | ValueObject other = (ValueObject)obj; 33 | IEnumerator thisValues = GetAtomicValues().GetEnumerator(); 34 | IEnumerator otherValues = other.GetAtomicValues().GetEnumerator(); 35 | while (thisValues.MoveNext() && otherValues.MoveNext()) 36 | { 37 | if (ReferenceEquals(thisValues.Current, null) ^ ReferenceEquals(otherValues.Current, null)) 38 | { 39 | return false; 40 | } 41 | if (thisValues.Current != null && !thisValues.Current.Equals(otherValues.Current)) 42 | { 43 | return false; 44 | } 45 | } 46 | return !thisValues.MoveNext() && !otherValues.MoveNext(); 47 | } 48 | 49 | public override int GetHashCode() 50 | { 51 | return GetAtomicValues() 52 | .Select(x => x != null ? x.GetHashCode() : 0) 53 | .Aggregate((x, y) => x ^ y); 54 | } 55 | 56 | public ValueObject GetCopy() 57 | { 58 | return this.MemberwiseClone() as ValueObject; 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /JieDDDFramework.Core/EntitySpecifications/ICreatedTimeState.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace JieDDDFramework.Core.EntitySpecifications 6 | { 7 | public interface ICreatedTimeState 8 | { 9 | DateTime CreatedTime { get; } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /JieDDDFramework.Core/EntitySpecifications/IDeletedState.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace JieDDDFramework.Core.EntitySpecifications 6 | { 7 | public interface IDeletedState 8 | { 9 | bool Deleted { get; } 10 | 11 | DateTime? DeletedTime { get; } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /JieDDDFramework.Core/EntitySpecifications/IModificationState.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace JieDDDFramework.Core.EntitySpecifications 6 | { 7 | public interface IModificationState 8 | { 9 | DateTime? ModifiedTime { get; set; } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /JieDDDFramework.Core/Exceptions/DomainException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace JieDDDFramework.Core.Exceptions 6 | { 7 | public class DomainException : Exception 8 | { 9 | public DomainException() 10 | { } 11 | 12 | public DomainException(string message) 13 | : base(message) 14 | { } 15 | 16 | public DomainException(string message, Exception innerException) 17 | : base(message, innerException) 18 | { } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /JieDDDFramework.Core/Exceptions/ExceptionExtension.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace JieDDDFramework.Core.Exceptions 6 | { 7 | public static class ExceptionExtension 8 | { 9 | public static string GetAllMessages(this Exception ex) 10 | { 11 | var exception = ex; 12 | var sb = new StringBuilder(); 13 | while (exception != null) 14 | { 15 | sb.AppendLine(exception.Message); 16 | exception = exception.InnerException; 17 | } 18 | return sb.ToString(); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /JieDDDFramework.Core/Exceptions/KnownException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace JieDDDFramework.Core.Exceptions 6 | { 7 | public class KnownException : Exception 8 | { 9 | public int ErrorCode { get; set; } 10 | 11 | public KnownException(string message, Exception innerException,int errorCode) : base(message, innerException) 12 | { 13 | ErrorCode = errorCode; 14 | } 15 | 16 | public KnownException(string message,Exception innerException) : base(message,innerException) 17 | { 18 | 19 | } 20 | 21 | public KnownException(string message,int errorCode) : base(message) 22 | { 23 | ErrorCode = errorCode; 24 | } 25 | 26 | public KnownException(string message) : base(message) 27 | { 28 | 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /JieDDDFramework.Core/Exceptions/ServiceAuthenticationException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace JieDDDFramework.Core.Exceptions 6 | { 7 | public class ServiceAuthenticationException : Exception 8 | { 9 | public string Content { get; } 10 | 11 | public ServiceAuthenticationException() 12 | { 13 | } 14 | 15 | public ServiceAuthenticationException(string content) 16 | { 17 | Content = content; 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /JieDDDFramework.Core/Exceptions/Utilities/Check.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.Linq; 5 | using System.Reflection; 6 | using System.Text; 7 | 8 | namespace JieDDDFramework.Core.Exceptions.Utilities 9 | { 10 | [DebuggerStepThrough] 11 | public static class Check 12 | { 13 | public static T NotNull(T value,string parameterName) 14 | { 15 | if ((object)value == null) 16 | { 17 | Check.NotEmpty(parameterName, nameof(parameterName)); 18 | throw new ArgumentNullException(parameterName); 19 | } 20 | return value; 21 | } 22 | 23 | public static IReadOnlyList NotEmpty(IReadOnlyList value, string parameterName) 24 | { 25 | Check.NotNull>(value, parameterName); 26 | if (value.Count == 0) 27 | { 28 | Check.NotEmpty(parameterName, nameof(parameterName)); 29 | } 30 | return value; 31 | } 32 | 33 | public static string NotEmpty(string value, string parameterName) 34 | { 35 | Exception exception = (Exception)null; 36 | if (value == null) 37 | exception = (Exception)new ArgumentNullException(parameterName); 38 | else if (value.Trim().Length == 0) 39 | exception = (Exception)new ArgumentException(parameterName); 40 | if (exception != null) 41 | { 42 | Check.NotEmpty(parameterName, nameof(parameterName)); 43 | throw exception; 44 | } 45 | return value; 46 | } 47 | 48 | public static string NullButNotEmpty(string value,string parameterName) 49 | { 50 | if (value != null && value.Length == 0) 51 | { 52 | Check.NotEmpty(parameterName, nameof(parameterName)); 53 | throw new ArgumentException(parameterName); 54 | } 55 | return value; 56 | } 57 | 58 | public static IReadOnlyList HasNoNulls(IReadOnlyList value, string parameterName) where T : class 59 | { 60 | NotNull(value, parameterName); 61 | if (value.Any(e => e == null)) 62 | { 63 | Check.NotEmpty(parameterName, nameof(parameterName)); 64 | throw new ArgumentException(parameterName); 65 | } 66 | return value; 67 | } 68 | 69 | public static T IsDefined(T value, string parameterName) where T : struct 70 | { 71 | if (!Enum.IsDefined(typeof(T), (object)value)) 72 | { 73 | Check.NotEmpty(parameterName, nameof(parameterName)); 74 | throw new ArgumentException(parameterName); 75 | } 76 | return value; 77 | } 78 | 79 | public static Type ValidEntityType(Type value, string parameterName) 80 | { 81 | if (!value.GetTypeInfo().IsClass) 82 | { 83 | Check.NotEmpty(parameterName, nameof(parameterName)); 84 | throw new ArgumentException(parameterName); 85 | } 86 | return value; 87 | } 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /JieDDDFramework.Core/Extensions/LinqSelectExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | 5 | namespace JieDDDFramework.Core.Extensions 6 | { 7 | public static class LinqSelectExtensions 8 | { 9 | public static IEnumerable> SelectTry(this IEnumerable enumerable, Func selector) 10 | { 11 | foreach (TSource element in enumerable) 12 | { 13 | SelectTryResult returnedValue; 14 | try 15 | { 16 | returnedValue = new SelectTryResult(element, selector(element), null); 17 | } 18 | catch (Exception ex) 19 | { 20 | returnedValue = new SelectTryResult(element, default(TResult), ex); 21 | } 22 | yield return returnedValue; 23 | } 24 | } 25 | 26 | public static IEnumerable OnCaughtException(this IEnumerable> enumerable, Func exceptionHandler) 27 | { 28 | return enumerable.Select(x => x.CaughtException == null ? x.Result : exceptionHandler(x.CaughtException)); 29 | } 30 | 31 | public static IEnumerable OnCaughtException(this IEnumerable> enumerable, Func exceptionHandler) 32 | { 33 | return enumerable.Select(x => x.CaughtException == null ? x.Result : exceptionHandler(x.Source, x.CaughtException)); 34 | } 35 | 36 | public class SelectTryResult 37 | { 38 | internal SelectTryResult(TSource source, TResult result, Exception exception) 39 | { 40 | Source = source; 41 | Result = result; 42 | CaughtException = exception; 43 | } 44 | 45 | public TSource Source { get; private set; } 46 | public TResult Result { get; private set; } 47 | public Exception CaughtException { get; private set; } 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /JieDDDFramework.Core/Extensions/TypeExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace JieDDDFramework.Core.Extensions 6 | { 7 | public static class TypeExtensions 8 | { 9 | public static bool IsInherit(this Type type, Type c) 10 | { 11 | if (type == c) return true; 12 | if (c.IsInterface) 13 | { 14 | foreach (var @interface in type.GetInterfaces()) 15 | { 16 | if (@interface == c) return true; 17 | if (@interface.IsGenericType && @interface.GetGenericTypeDefinition() == c) return true; 18 | if (IsInherit(@interface,c)) return true; 19 | } 20 | return false; 21 | } 22 | if (type.BaseType == null) return false; 23 | if (type.BaseType == c) return true; 24 | if (type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == c) return true; 25 | return IsInherit(type.BaseType, c); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /JieDDDFramework.Core/JieDDDFramework.Core.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /JieDDDFramework.Core/MediatR/Behaviors/LoggingBehavior.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | using MediatR; 7 | using Microsoft.Extensions.Logging; 8 | 9 | namespace JieDDDFramework.Core.MediatR.Behaviors 10 | { 11 | public class LoggingBehavior : IPipelineBehavior 12 | { 13 | private readonly ILogger> _logger; 14 | public LoggingBehavior(ILogger> logger) => _logger = logger; 15 | public async Task Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate next) 16 | { 17 | _logger.LogInformation($"Handling {typeof(TRequest).Name}"); 18 | var response = await next(); 19 | _logger.LogInformation($"Handled {typeof(TResponse).Name}"); 20 | return response; 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /JieDDDFramework.Core/MediatR/Behaviors/ValidatorBehavior.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | using FluentValidation; 8 | using JieDDDFramework.Core.Exceptions; 9 | using MediatR; 10 | 11 | namespace JieDDDFramework.Core.MediatR.Behaviors 12 | { 13 | public class ValidatorBehavior : IPipelineBehavior 14 | { 15 | private readonly IValidator[] _validators; 16 | 17 | public ValidatorBehavior(IValidator[] validators) => _validators = validators; 18 | 19 | public async Task Handle(TRequest request, CancellationToken cancellationToken,RequestHandlerDelegate next) 20 | { 21 | var failures = _validators 22 | .Select(v => v.Validate(request)) 23 | .SelectMany(result => result.Errors) 24 | .Where(x => x != null) 25 | .ToList(); 26 | 27 | if (failures.Any()) 28 | { 29 | throw new KnownException( 30 | $"Command Validation Errors for type {typeof(TRequest).Name}", new ValidationException("Validation exception", failures)); 31 | } 32 | 33 | var response = await next(); 34 | return response; 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /JieDDDFramework.Core/MediatR/MediatRExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using JieDDDFramework.Core.MediatR.Behaviors; 5 | using MediatR; 6 | using Microsoft.Extensions.DependencyInjection; 7 | 8 | namespace JieDDDFramework.Core.MediatR 9 | { 10 | public static class MediatRExtensions 11 | { 12 | public static IServiceCollection AddDefaultMediatRBehaviors(this IServiceCollection services) 13 | { 14 | services.AddSingleton(typeof(IPipelineBehavior<,>), typeof(LoggingBehavior<,>)); 15 | services.AddSingleton(typeof(IPipelineBehavior<,>), typeof(ValidatorBehavior<,>)); 16 | return services; 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /JieDDDFramework.Core/MediatR/NoMediator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | using MediatR; 7 | 8 | namespace JieDDDFramework.Core.MediatR 9 | { 10 | public class NoMediator : IMediator 11 | { 12 | public Task Publish(object notification, CancellationToken cancellationToken = new CancellationToken()) 13 | { 14 | return Task.CompletedTask; 15 | } 16 | 17 | public Task Publish(TNotification notification, CancellationToken cancellationToken = default(CancellationToken)) where TNotification : INotification 18 | { 19 | return Task.CompletedTask; 20 | } 21 | 22 | public Task Send(IRequest request, CancellationToken cancellationToken = default(CancellationToken)) 23 | { 24 | return Task.FromResult(default(TResponse)); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /JieDDDFramework.Core/Models/ApiResult.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace JieDDDFramework.Core.Models 6 | { 7 | public class ApiResult : Result 8 | { 9 | /// 10 | /// Code定义规则请参加API文档 11 | /// 12 | public int Code { get; set; } 13 | } 14 | 15 | public class ApiResult : ApiResult, IResult 16 | { 17 | #region Implementation of ICustomResult 18 | 19 | public T Value { get; set; } 20 | 21 | #endregion 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /JieDDDFramework.Core/Models/IPagedList`1.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace JieDDDFramework.Core.Models 6 | { 7 | public interface IPagedList 8 | { 9 | int PageIndex { get; set; } 10 | 11 | int PageSize { get; set; } 12 | 13 | int TotalCount { get; set; } 14 | 15 | int TotalPages { get; set; } 16 | 17 | bool HasPreviousPage { get; } 18 | 19 | bool HasNextPage { get; } 20 | 21 | List Rows { get; set; } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /JieDDDFramework.Core/Models/IPagerBase.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace JieDDDFramework.Core.Models 6 | { 7 | public interface IPagerBase 8 | { 9 | int PageIndex { get; set; } 10 | 11 | int PageSize { get; set; } 12 | 13 | int PageNumber { get; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /JieDDDFramework.Core/Models/IPagerQuery.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace JieDDDFramework.Core.Models 6 | { 7 | public interface IPagerQueryParameter : IPagerBase 8 | { 9 | List OrderSorts { get; set; } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /JieDDDFramework.Core/Models/IResult.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace JieDDDFramework.Core.Models 6 | { 7 | public interface IResult 8 | { 9 | bool Success { get; set; } 10 | 11 | string Message { get; set; } 12 | 13 | void Succeed(); 14 | 15 | void Fail(); 16 | 17 | void Succeed(string message); 18 | 19 | void Fail(string message); 20 | } 21 | 22 | public interface IResult : IResult 23 | { 24 | T Value { get; set; } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /JieDDDFramework.Core/Models/PageOrders.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace JieDDDFramework.Core.Models 6 | { 7 | public class PageOrders 8 | { 9 | public string OrderName { get; set; } 10 | 11 | public PageOrderType OrderType { get; set; } 12 | } 13 | 14 | public enum PageOrderType : uint 15 | { 16 | Asc = 0, 17 | Desc = 1 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /JieDDDFramework.Core/Models/PagedList`1.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | 7 | namespace JieDDDFramework.Core.Models 8 | { 9 | public class PagedList : IPagedList 10 | { 11 | public List Rows { get; set; } 12 | 13 | public PagedList() 14 | { 15 | Rows = new List(); 16 | } 17 | 18 | public PagedList(IQueryable source, int pageIndex, int pageSize) 19 | { 20 | var total = source.Count(); 21 | TotalCount = total; 22 | TotalPages = total / pageSize; 23 | 24 | if (total % pageSize > 0) 25 | TotalPages++; 26 | 27 | PageSize = pageSize; 28 | PageIndex = pageIndex; 29 | Rows = new List(); 30 | Rows.AddRange(source.Skip(pageIndex * pageSize).Take(pageSize).ToList()); 31 | } 32 | 33 | public PagedList(IList source, int pageIndex, int pageSize) 34 | { 35 | TotalCount = source.Count(); 36 | TotalPages = TotalCount / pageSize; 37 | 38 | if (TotalCount % pageSize > 0) 39 | TotalPages++; 40 | 41 | PageSize = pageSize; 42 | PageIndex = pageIndex; 43 | Rows = new List(); 44 | Rows.AddRange(source.Skip(pageIndex * pageSize).Take(pageSize).ToList()); 45 | } 46 | 47 | public PagedList(IEnumerable source, int pageIndex, int pageSize, int totalCount) 48 | { 49 | TotalCount = totalCount; 50 | TotalPages = TotalCount / pageSize; 51 | 52 | if (TotalCount % pageSize > 0) 53 | TotalPages++; 54 | 55 | PageSize = pageSize; 56 | PageIndex = pageIndex; 57 | Rows = new List(); 58 | Rows.AddRange(source); 59 | } 60 | 61 | public int PageIndex { get; set; } 62 | 63 | public int PageSize { get; set; } 64 | 65 | public int TotalCount { get; set; } 66 | 67 | public int TotalPages { get; set; } 68 | 69 | public bool HasPreviousPage => (PageIndex > 0); 70 | 71 | public bool HasNextPage => (PageIndex + 1 < TotalPages); 72 | } 73 | 74 | public static class PagedListExtensions 75 | { 76 | public static IPagedList ToPageResult(this IQueryable query, int pageIndex, int pageSize, bool findTotalCount = true) 77 | { 78 | var pageResult = new PagedList(); 79 | if (findTotalCount) 80 | { 81 | var totalCount = query.Count(); 82 | var totalPages = totalCount / pageSize; 83 | pageResult.TotalPages = totalCount % pageSize == 0 ? totalPages : totalPages + 1; 84 | pageResult.TotalCount = totalCount; 85 | } 86 | pageResult.Rows = query.Skip(pageIndex * pageSize).Take(pageSize).ToList(); 87 | pageResult.PageIndex = pageIndex; 88 | pageResult.PageSize = pageSize; 89 | return pageResult; 90 | } 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /JieDDDFramework.Core/Models/Result.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace JieDDDFramework.Core.Models 6 | { 7 | public class Result : IResult 8 | { 9 | #region Implementation of ICustomResult 10 | 11 | public bool Success { get; set; } 12 | 13 | public string Message { get; set; } 14 | 15 | public void Succeed() 16 | { 17 | Success = true; 18 | } 19 | 20 | public void Fail() 21 | { 22 | Success = false; 23 | } 24 | 25 | public void Succeed(string message) 26 | { 27 | Success = true; 28 | Message = message; 29 | } 30 | 31 | public void Fail(string message) 32 | { 33 | Success = false; 34 | Message = message; 35 | } 36 | 37 | #endregion 38 | } 39 | 40 | public class Result : Result, IResult 41 | { 42 | #region Implementation of ICustomResult 43 | 44 | public T Value { get; set; } 45 | 46 | #endregion 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /JieDDDFramework.Core/RequestProvider/HttpRequestExceptionEx.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Net.Http; 4 | using System.Text; 5 | 6 | namespace JieDDDFramework.Core.RequestProvider 7 | { 8 | public class HttpRequestExceptionEx : HttpRequestException 9 | { 10 | public System.Net.HttpStatusCode HttpCode { get; } 11 | public HttpRequestExceptionEx(System.Net.HttpStatusCode code) : this(code, null, null) 12 | { 13 | } 14 | 15 | public HttpRequestExceptionEx(System.Net.HttpStatusCode code, string message) : this(code, message, null) 16 | { 17 | } 18 | 19 | public HttpRequestExceptionEx(System.Net.HttpStatusCode code, string message, Exception inner) : base(message, 20 | inner) 21 | { 22 | HttpCode = code; 23 | } 24 | 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /JieDDDFramework.Core/RequestProvider/IRequestProvider.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace JieDDDFramework.Core.RequestProvider 7 | { 8 | public interface IRequestProvider 9 | { 10 | Task GetAsync(string uri, string token = ""); 11 | 12 | Task PostAsync(string uri, TResult data, string token = "", string header = ""); 13 | 14 | Task PostAsync(string uri, string data, string token = "", string header = ""); 15 | 16 | Task PutAsync(string uri, TResult data, string token = "", string header = ""); 17 | 18 | Task DeleteAsync(string uri, string token = ""); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /JieDDDFramework.Core/RequestProvider/RequestProvider.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Net; 4 | using System.Net.Http; 5 | using System.Net.Http.Headers; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | using JieDDDFramework.Core.Exceptions; 9 | using Newtonsoft.Json; 10 | using Newtonsoft.Json.Converters; 11 | using Newtonsoft.Json.Serialization; 12 | 13 | namespace JieDDDFramework.Core.RequestProvider 14 | { 15 | public class RequestProvider : IRequestProvider 16 | { 17 | private readonly JsonSerializerSettings _serializerSettings; 18 | 19 | public RequestProvider() 20 | { 21 | _serializerSettings = new JsonSerializerSettings 22 | { 23 | ContractResolver = new CamelCasePropertyNamesContractResolver(), 24 | DateTimeZoneHandling = DateTimeZoneHandling.Utc, 25 | NullValueHandling = NullValueHandling.Ignore 26 | }; 27 | _serializerSettings.Converters.Add(new StringEnumConverter()); 28 | } 29 | 30 | public async Task GetAsync(string uri, string token = "") 31 | { 32 | HttpClient httpClient = CreateHttpClient(token); 33 | HttpResponseMessage response = await httpClient.GetAsync(uri); 34 | 35 | await HandleResponse(response); 36 | string serialized = await response.Content.ReadAsStringAsync(); 37 | 38 | TResult result = await Task.Run(() => 39 | JsonConvert.DeserializeObject(serialized, _serializerSettings)); 40 | 41 | return result; 42 | } 43 | 44 | public async Task PostAsync(string uri, TResult data, string token = "", string header = "") 45 | { 46 | HttpClient httpClient = CreateHttpClient(token); 47 | 48 | if (!string.IsNullOrEmpty(header)) 49 | { 50 | AddHeaderParameter(httpClient, header); 51 | } 52 | 53 | var content = new StringContent(JsonConvert.SerializeObject(data)); 54 | content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); 55 | HttpResponseMessage response = await httpClient.PostAsync(uri, content); 56 | 57 | await HandleResponse(response); 58 | string serialized = await response.Content.ReadAsStringAsync(); 59 | 60 | TResult result = await Task.Run(() => 61 | JsonConvert.DeserializeObject(serialized, _serializerSettings)); 62 | 63 | return result; 64 | } 65 | 66 | public async Task PostAsync(string uri, string data, string clientId, string clientSecret) 67 | { 68 | HttpClient httpClient = CreateHttpClient(string.Empty); 69 | 70 | var content = new StringContent(data); 71 | content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); 72 | HttpResponseMessage response = await httpClient.PostAsync(uri, content); 73 | 74 | await HandleResponse(response); 75 | string serialized = await response.Content.ReadAsStringAsync(); 76 | 77 | TResult result = await Task.Run(() => 78 | JsonConvert.DeserializeObject(serialized, _serializerSettings)); 79 | 80 | return result; 81 | } 82 | 83 | public async Task PutAsync(string uri, TResult data, string token = "", string header = "") 84 | { 85 | HttpClient httpClient = CreateHttpClient(token); 86 | 87 | if (!string.IsNullOrEmpty(header)) 88 | { 89 | AddHeaderParameter(httpClient, header); 90 | } 91 | 92 | var content = new StringContent(JsonConvert.SerializeObject(data)); 93 | content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); 94 | HttpResponseMessage response = await httpClient.PutAsync(uri, content); 95 | 96 | await HandleResponse(response); 97 | string serialized = await response.Content.ReadAsStringAsync(); 98 | 99 | TResult result = await Task.Run(() => 100 | JsonConvert.DeserializeObject(serialized, _serializerSettings)); 101 | 102 | return result; 103 | } 104 | 105 | public async Task DeleteAsync(string uri, string token = "") 106 | { 107 | HttpClient httpClient = CreateHttpClient(token); 108 | await httpClient.DeleteAsync(uri); 109 | } 110 | 111 | private HttpClient CreateHttpClient(string token = "") 112 | { 113 | var httpClient = new HttpClient(); 114 | httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 115 | 116 | if (!string.IsNullOrEmpty(token)) 117 | { 118 | httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); 119 | } 120 | return httpClient; 121 | } 122 | 123 | private void AddHeaderParameter(HttpClient httpClient, string parameter) 124 | { 125 | if (httpClient == null) 126 | return; 127 | 128 | if (string.IsNullOrEmpty(parameter)) 129 | return; 130 | 131 | httpClient.DefaultRequestHeaders.Add(parameter, Guid.NewGuid().ToString()); 132 | } 133 | 134 | private async Task HandleResponse(HttpResponseMessage response) 135 | { 136 | if (!response.IsSuccessStatusCode) 137 | { 138 | var content = await response.Content.ReadAsStringAsync(); 139 | 140 | if (response.StatusCode == HttpStatusCode.Forbidden || 141 | response.StatusCode == HttpStatusCode.Unauthorized) 142 | { 143 | throw new ServiceAuthenticationException(content); 144 | } 145 | 146 | throw new HttpRequestExceptionEx(response.StatusCode, content); 147 | } 148 | } 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /JieDDDFramework.Data.EntityFramework/AopConfigurations/EFInterceptor.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | using AspectCore.DynamicProxy; 6 | using JieDDDFramework.Data.EntityFramework.ModelConfigurations; 7 | using Microsoft.EntityFrameworkCore; 8 | using Microsoft.Extensions.DependencyInjection; 9 | 10 | namespace JieDDDFramework.Data.EntityFramework.AopConfigurations 11 | { 12 | //public class EFInterceptor : AbstractInterceptor 13 | //{ 14 | // public override async Task Invoke(AspectContext context, AspectDelegate next) 15 | // { 16 | // var modelConfigurationProvider = context.ServiceProvider.GetService(); 17 | // if (modelConfigurationProvider == null) 18 | // { 19 | // throw new ArgumentNullException(nameof(modelConfigurationProvider)); 20 | // } 21 | 22 | // var modelBuilder = (ModelBuilder) context.Parameters[0]; 23 | // var dbContext = (Microsoft.EntityFrameworkCore.DbContext) context.Proxy; 24 | // modelConfigurationProvider.GetFixModelConfigurationService().FixModel(modelBuilder, dbContext); 25 | // modelConfigurationProvider.GetGlobalFilterService().QueryFilter(modelBuilder, dbContext); 26 | // modelConfigurationProvider.GetApplyConfigurationService().AutoApplyConfiguration(modelBuilder,dbContext); 27 | // await context.Invoke(next); 28 | 29 | // } 30 | //} 31 | } 32 | -------------------------------------------------------------------------------- /JieDDDFramework.Data.EntityFramework/AopConfigurations/ServiceContainerExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using AspectCore.Configuration; 5 | using AspectCore.Injector; 6 | using Autofac; 7 | 8 | namespace JieDDDFramework.Data.EntityFramework.AopConfigurations 9 | { 10 | public static class ServiceContainerExtensions 11 | { 12 | public static InterceptorCollection ConfigureEFInterceptors(this InterceptorCollection interceptorCollection) 13 | { 14 | //由于EF自动生成的迁移类会寻找DbContext派生类所在的命名空间,当启用AspectCore的AOP功能后DbContext将会被代理到AspectCore中 15 | //暂时注释掉 16 | //interceptorCollection.AddTyped(Predicates.ForMethod("*DbContext", "OnModelCreating")); 17 | 18 | return interceptorCollection; 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /JieDDDFramework.Data.EntityFramework/DbContext/DomainDbContext.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | using JieDDDFramework.Core.Domain; 7 | using JieDDDFramework.Data.EntityFramework.ModelConfigurations; 8 | using MediatR; 9 | using Microsoft.EntityFrameworkCore; 10 | 11 | namespace JieDDDFramework.Data.EntityFramework.DbContext 12 | { 13 | public abstract class DomainDbContext :Microsoft.EntityFrameworkCore.DbContext, IUnitOfWork 14 | { 15 | protected readonly IMediator Mediator; 16 | protected readonly IModelConfigurationProvider ModelConfigurationProvider; 17 | 18 | protected DomainDbContext(DbContextOptions options, IMediator mediator, IModelConfigurationProvider modelConfigurationProvider) : base(options) 19 | { 20 | Mediator = mediator ?? throw new ArgumentException(nameof(mediator)); 21 | ModelConfigurationProvider = modelConfigurationProvider; 22 | } 23 | 24 | protected DomainDbContext(DbContextOptions options, IMediator mediator) : base(options) 25 | { 26 | Mediator = mediator ?? throw new ArgumentException(nameof(mediator)); 27 | } 28 | 29 | public async Task SaveEntitiesAsync(CancellationToken cancellationToken = default(CancellationToken)) 30 | { 31 | await Mediator.DispatchDomainEventsAsync(this); 32 | await base.SaveChangesAsync(cancellationToken); 33 | return true; 34 | } 35 | 36 | protected override void OnModelCreating(ModelBuilder modelBuilder) 37 | { 38 | if (ModelConfigurationProvider != null) 39 | { 40 | ModelConfigurationProvider.GetFixModelConfigurationService().FixModel(modelBuilder, this); 41 | ModelConfigurationProvider.GetGlobalFilterService().QueryFilter(modelBuilder, this); 42 | ModelConfigurationProvider.GetApplyConfigurationService().AutoApplyConfiguration(modelBuilder, this); 43 | } 44 | base.OnModelCreating(modelBuilder); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /JieDDDFramework.Data.EntityFramework/EntitySpecificationExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using JieDDDFramework.Core.EntitySpecifications; 6 | 7 | namespace JieDDDFramework.Data.EntityFramework 8 | { 9 | public static class EntitySpecificationExtensions 10 | { 11 | /// 12 | /// 时间区间查询 13 | /// 14 | /// 15 | /// 创建时间区间 16 | /// 17 | public static IQueryable WhereBetweenTime(this IQueryable query, DateTime[] createdTimeRange) where T : class, ICreatedTimeState 18 | { 19 | if (createdTimeRange == null || createdTimeRange.Contains(DateTime.MinValue)) 20 | return query; 21 | 22 | var beginTime = createdTimeRange[0]; 23 | var endTime = createdTimeRange[1]; 24 | 25 | if (beginTime < endTime) 26 | { 27 | endTime = endTime.AddDays(1); 28 | return query.Where(x => x.CreatedTime >= beginTime && x.CreatedTime <= endTime); 29 | } 30 | if (beginTime > endTime) 31 | { 32 | beginTime = beginTime.AddDays(1); 33 | return query.Where(x => x.CreatedTime <= beginTime && x.CreatedTime >= endTime); 34 | } 35 | if (beginTime == endTime || createdTimeRange.Length == 1) 36 | {//查询某天数据 37 | endTime = endTime.AddDays(1); 38 | return query.Where(x => x.CreatedTime >= beginTime && x.CreatedTime <= endTime); 39 | } 40 | 41 | return query; 42 | } 43 | 44 | public static IQueryable WhereNotDelete(this IQueryable query) where T : class, IDeletedState 45 | { 46 | return query.Where(x => x.Deleted == false); 47 | } 48 | 49 | public static IOrderedQueryable OrderByCreatedTime(this IQueryable query, bool desc = true) 50 | where T : class, ICreatedTimeState 51 | { 52 | return query.OrderByDescending(x => x.CreatedTime); 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /JieDDDFramework.Data.EntityFramework/JieDDDFramework.Data.EntityFramework.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | ..\..\..\..\..\..\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.csharp\4.5.0\ref\netstandard2.0\Microsoft.CSharp.dll 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /JieDDDFramework.Data.EntityFramework/MediatorExtension.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using JieDDDFramework.Core.Domain; 7 | using JieDDDFramework.Data.EntityFramework.DbContext; 8 | using MediatR; 9 | 10 | namespace JieDDDFramework.Data.EntityFramework 11 | { 12 | static class MediatorExtension 13 | { 14 | public static async Task DispatchDomainEventsAsync(this IMediator mediator, DomainDbContext ctx) 15 | { 16 | var domainEntities = ctx.ChangeTracker 17 | .Entries() 18 | .Where(x => x.Entity.DomainEvents != null && x.Entity.DomainEvents.Any()); 19 | 20 | var domainEvents = domainEntities 21 | .SelectMany(x => x.Entity.DomainEvents) 22 | .ToList(); 23 | 24 | domainEntities.ToList() 25 | .ForEach(entity => entity.Entity.ClearDomainEvents()); 26 | 27 | var tasks = domainEvents 28 | .Select(async (domainEvent) => { 29 | await mediator.Publish(domainEvent); 30 | }); 31 | 32 | await Task.WhenAll(tasks); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /JieDDDFramework.Data.EntityFramework/Migrate/IDbContextSeed.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | 3 | namespace JieDDDFramework.Data.EntityFramework.Migrate 4 | { 5 | public interface IDbContextSeed where TDbContext : Microsoft.EntityFrameworkCore.DbContext 6 | { 7 | Task SeedAsync(TDbContext context); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /JieDDDFramework.Data.EntityFramework/Migrate/MigrateBuilder.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using Microsoft.Extensions.DependencyInjection; 5 | 6 | namespace JieDDDFramework.Data.EntityFramework.Migrate 7 | { 8 | public class MigrateBuilder 9 | { 10 | public MigrateBuilder(IServiceCollection services) 11 | { 12 | Services = services ?? throw new ArgumentNullException(nameof(services)); 13 | } 14 | public IServiceCollection Services { get; } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /JieDDDFramework.Data.EntityFramework/Migrate/MigrateBuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using Microsoft.Extensions.DependencyInjection; 5 | using Microsoft.Extensions.DependencyInjection.Extensions; 6 | 7 | namespace JieDDDFramework.Data.EntityFramework.Migrate 8 | { 9 | public static class MigrateBuilderExtensions 10 | { 11 | public static MigrateBuilder AddDbSeed(this MigrateBuilder builder, IDbContextSeed dbContextSeed) where TDbContext : Microsoft.EntityFrameworkCore.DbContext 12 | { 13 | builder.Services.AddSingleton(dbContextSeed); 14 | return builder; 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /JieDDDFramework.Data.EntityFramework/Migrate/MigrateConfigurations.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace JieDDDFramework.Data.EntityFramework.Migrate 6 | { 7 | public class MigrateOptions 8 | { 9 | public bool Enabled { get; set; }= false; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /JieDDDFramework.Data.EntityFramework/Migrate/MigrateDbContextExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Data.SqlClient; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using JieDDDFramework.Module.Identity.Data; 7 | using Microsoft.EntityFrameworkCore; 8 | using Microsoft.EntityFrameworkCore.Metadata.Conventions; 9 | using Microsoft.Extensions.DependencyInjection; 10 | using Microsoft.Extensions.DependencyInjection.Extensions; 11 | using Microsoft.Extensions.Logging; 12 | using Polly; 13 | 14 | namespace JieDDDFramework.Data.EntityFramework.Migrate 15 | { 16 | public static class MigrateDbContextExtensions 17 | { 18 | public static MigrateBuilder AddMigrateService(this IServiceCollection services,Action setupAction = null) 19 | { 20 | var option = new MigrateOptions() 21 | { 22 | Enabled = true 23 | }; 24 | setupAction?.Invoke(option); 25 | services.TryAddSingleton(option); 26 | return new MigrateBuilder(services); 27 | } 28 | 29 | public static IServiceProvider MigrateDbContext(this IServiceProvider serviceProvider, 30 | Action seeder = null) where TContext : Microsoft.EntityFrameworkCore.DbContext 31 | { 32 | 33 | using (var scope = serviceProvider.CreateScope()) 34 | { 35 | var services = scope.ServiceProvider; 36 | var options = services.GetService(); 37 | if (options == null || !options.Enabled) 38 | { 39 | return serviceProvider; 40 | } 41 | 42 | var logger = services.GetRequiredService>(); 43 | 44 | var context = services.GetService(); 45 | 46 | try 47 | { 48 | logger.LogInformation($"DbContext=>{typeof(TContext).Name} 迁移开始"); 49 | 50 | var retry = Policy.Handle() 51 | .WaitAndRetry(new TimeSpan[] 52 | { 53 | TimeSpan.FromSeconds(3), 54 | TimeSpan.FromSeconds(5), 55 | TimeSpan.FromSeconds(8), 56 | }); 57 | 58 | retry.Execute(() => 59 | { 60 | context.Database.Migrate(); 61 | var dbContextSeed = services.GetService>(); 62 | dbContextSeed?.SeedAsync(context).Wait(); 63 | seeder?.Invoke(context, services); 64 | }); 65 | logger.LogInformation($"DbContext=>{typeof(TContext).Name} 迁移完成"); 66 | } 67 | catch (Exception ex) 68 | { 69 | logger.LogError(ex, $"在DbContext=>{typeof(TContext).Name} 中迁移数据库出错"); 70 | } 71 | } 72 | 73 | return serviceProvider; 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /JieDDDFramework.Data.EntityFramework/ModelConfigurations/DDDEntityTypeConfiguration.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using JieDDDFramework.Core.Domain; 5 | using Microsoft.EntityFrameworkCore; 6 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 7 | 8 | namespace JieDDDFramework.Data.EntityFramework.ModelConfigurations 9 | { 10 | public abstract class DDDEntityTypeConfiguration : IEntityTypeConfiguration where TEntity : class,IEntity 11 | { 12 | public virtual void Configure(EntityTypeBuilder configuration) 13 | { 14 | configuration.Ignore(b => b.DomainEvents); 15 | Map(configuration); 16 | } 17 | 18 | public abstract void Map(EntityTypeBuilder configuration); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /JieDDDFramework.Data.EntityFramework/ModelConfigurations/DefaultModelConfigurationProvider.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using JieDDDFramework.Data.EntityFramework.ModelConfigurations.Services; 5 | 6 | namespace JieDDDFramework.Data.EntityFramework.ModelConfigurations 7 | { 8 | public class DefaultModelConfigurationProvider : IModelConfigurationProvider 9 | { 10 | private readonly IAutoApplyConfigurationService _autoApplyConfigurationService; 11 | private readonly IFixModelConfigurationService _fixModelConfigurationService; 12 | private readonly IGlobalFilterService _globalFilterService; 13 | 14 | public DefaultModelConfigurationProvider(IAutoApplyConfigurationService autoApplyConfigurationService, IFixModelConfigurationService fixModelConfigurationService, IGlobalFilterService globalFilterService) 15 | { 16 | _autoApplyConfigurationService = autoApplyConfigurationService; 17 | _fixModelConfigurationService = fixModelConfigurationService; 18 | _globalFilterService = globalFilterService; 19 | } 20 | public IAutoApplyConfigurationService GetApplyConfigurationService() 21 | { 22 | return _autoApplyConfigurationService; 23 | } 24 | 25 | public IFixModelConfigurationService GetFixModelConfigurationService() 26 | { 27 | return _fixModelConfigurationService; 28 | } 29 | 30 | public IGlobalFilterService GetGlobalFilterService() 31 | { 32 | return _globalFilterService; 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /JieDDDFramework.Data.EntityFramework/ModelConfigurations/IModelConfigurationProvider.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using JieDDDFramework.Data.EntityFramework.ModelConfigurations.Services; 5 | 6 | namespace JieDDDFramework.Data.EntityFramework.ModelConfigurations 7 | { 8 | public interface IModelConfigurationProvider 9 | { 10 | IGlobalFilterService GetGlobalFilterService(); 11 | IFixModelConfigurationService GetFixModelConfigurationService(); 12 | IAutoApplyConfigurationService GetApplyConfigurationService(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /JieDDDFramework.Data.EntityFramework/ModelConfigurations/ModelBuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Reflection; 5 | using System.Text; 6 | using AspectCore.Extensions.Reflection; 7 | using JieDDDFramework.Core.Extensions; 8 | using Microsoft.EntityFrameworkCore; 9 | using Microsoft.EntityFrameworkCore.Design; 10 | 11 | namespace JieDDDFramework.Data.EntityFramework.ModelConfigurations 12 | { 13 | public static class ModelBuilderExtensions 14 | { 15 | public static void AutoApplyConfiguration(this ModelBuilder modelBuilder, TDbContext dbContext, 16 | string @namespace = null) where TDbContext : Microsoft.EntityFrameworkCore.DbContext 17 | { 18 | var typesToRegister = dbContext.GetType().Assembly.GetTypes() 19 | .Where(x=>!x.IsAbstract&& x.IsInherit(typeof(IEntityTypeConfiguration<>))) 20 | .Where(x => string.IsNullOrEmpty(@namespace) || x.Namespace == @namespace); 21 | foreach (var type in typesToRegister) 22 | { 23 | var constructorInfo = type.GetTypeInfo().GetConstructor(new Type[0]); 24 | var reflector = constructorInfo.GetReflector(); 25 | dynamic configurationInstance = reflector.Invoke(); 26 | //dynamic configurationInstance = Activator.CreateInstance(type); 27 | modelBuilder.ApplyConfiguration(configurationInstance); 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /JieDDDFramework.Data.EntityFramework/ModelConfigurations/ModelConfigurationExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using JieDDDFramework.Data.EntityFramework.AopConfigurations; 5 | using JieDDDFramework.Data.EntityFramework.ModelConfigurations.Services; 6 | using Microsoft.Extensions.DependencyInjection; 7 | using Microsoft.Extensions.DependencyInjection.Extensions; 8 | 9 | namespace JieDDDFramework.Data.EntityFramework.ModelConfigurations 10 | { 11 | public static class ModelConfigurationExtensions 12 | { 13 | public static IServiceCollection AddEFModelConfiguration(this IServiceCollection service, 14 | Action setupAction = null) 15 | { 16 | var option = new ModelConfigurationOption(); 17 | setupAction?.Invoke(option); 18 | service.TryAddSingleton(option); 19 | if (setupAction != null) 20 | { 21 | service.Configure(setupAction); 22 | } 23 | else 24 | { 25 | service.Configure(_=>{}); 26 | } 27 | service.TryAddTransient(); 28 | service.TryAddTransient(); 29 | service.TryAddTransient(); 30 | service.TryAddTransient(); 31 | return service; 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /JieDDDFramework.Data.EntityFramework/ModelConfigurations/ModelConfigurationOption.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using Microsoft.EntityFrameworkCore; 5 | 6 | namespace JieDDDFramework.Data.EntityFramework.ModelConfigurations 7 | { 8 | public class ModelConfigurationOption 9 | { 10 | /// 11 | /// 默认过滤字段集合 12 | /// 13 | public List QueryFilterFields = new List() {"IsDeleted"}; 14 | 15 | /// 16 | /// 自动注册时根据不同的DbContext类型来指定其所在的命名空间 /> 17 | /// 18 | public Dictionary DbModelConfigurationNamespaceDictionary = new Dictionary(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /JieDDDFramework.Data.EntityFramework/ModelConfigurations/Services/DefaultAutoApplyConfigurationService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Reflection; 5 | using System.Text; 6 | using Microsoft.EntityFrameworkCore; 7 | using Microsoft.Extensions.Options; 8 | 9 | namespace JieDDDFramework.Data.EntityFramework.ModelConfigurations.Services 10 | { 11 | public class DefaultAutoApplyConfigurationService : IAutoApplyConfigurationService 12 | { 13 | private readonly ModelConfigurationOption _option; 14 | public DefaultAutoApplyConfigurationService(IOptions option) 15 | { 16 | _option = option.Value; 17 | } 18 | 19 | public void AutoApplyConfiguration(ModelBuilder modelBuilder, TDbContext dbContext) 20 | where TDbContext : Microsoft.EntityFrameworkCore.DbContext 21 | { 22 | var @namespace = _option.DbModelConfigurationNamespaceDictionary.Where(x => x.Key == dbContext.GetType()) 23 | .Select(x => x.Value).FirstOrDefault(); 24 | modelBuilder.AutoApplyConfiguration(dbContext, @namespace); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /JieDDDFramework.Data.EntityFramework/ModelConfigurations/Services/DefaultFixModelConfigurationService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using JieDDDFramework.Core.Domain; 6 | using Microsoft.EntityFrameworkCore; 7 | using Microsoft.EntityFrameworkCore.Metadata.Internal; 8 | 9 | namespace JieDDDFramework.Data.EntityFramework.ModelConfigurations.Services 10 | { 11 | public class DefaultFixModelConfigurationService : IFixModelConfigurationService 12 | { 13 | public void FixModel(ModelBuilder modelBuilder, TDbContext dbContext) where TDbContext : Microsoft.EntityFrameworkCore.DbContext 14 | { 15 | SetIdLengthLimit(modelBuilder); 16 | } 17 | 18 | protected virtual void SetIdLengthLimit(ModelBuilder builder) 19 | { 20 | foreach (var entityType in builder.Model.GetEntityTypes().Where(x=>x.ClrType!=null&&x.ClrType.GetInterfaces().Contains(typeof(IEntity)))) 21 | { 22 | var keys = entityType.FindPrimaryKey(); 23 | if (keys == null) 24 | { 25 | foreach (var property in entityType.GetProperties().Where(x => x.ClrType == typeof(string))) 26 | { 27 | var propertyBuilder =builder.Entity(entityType.ClrType).Property(property.Name); 28 | var length = propertyBuilder.Metadata.GetMaxLength(); 29 | if (length == null) 30 | { 31 | propertyBuilder.HasMaxLength(64); 32 | } 33 | } 34 | continue; 35 | } 36 | foreach (var mutableProperty in keys.Properties) 37 | { 38 | try 39 | { 40 | if (mutableProperty.ClrType == typeof(string)) 41 | { 42 | builder.Entity(entityType.ClrType).Property(mutableProperty.Name).HasMaxLength(64); 43 | } 44 | } 45 | catch(Exception ) 46 | { 47 | } 48 | } 49 | } 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /JieDDDFramework.Data.EntityFramework/ModelConfigurations/Services/DefaultGlobalFilterService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Linq.Expressions; 5 | using System.Security.Cryptography.X509Certificates; 6 | using System.Text; 7 | using JieDDDFramework.Core.Domain; 8 | using Microsoft.EntityFrameworkCore; 9 | using Microsoft.Extensions.Options; 10 | 11 | namespace JieDDDFramework.Data.EntityFramework.ModelConfigurations.Services 12 | { 13 | public class DefaultGlobalFilterService: IGlobalFilterService 14 | { 15 | private readonly ModelConfigurationOption _option; 16 | public DefaultGlobalFilterService(IOptions option) 17 | { 18 | _option = option.Value; 19 | } 20 | public void QueryFilter(ModelBuilder modelBuilder, TDbContext dbContext) where TDbContext : Microsoft.EntityFrameworkCore.DbContext 21 | { 22 | foreach (var mutableEntityType in modelBuilder.Model.GetEntityTypes().Where(x => x.ClrType != null && x.ClrType.GetInterfaces().Contains(typeof(IEntity)))) 23 | { 24 | foreach (var mutableProperty in mutableEntityType.GetProperties().Where(x => _option.QueryFilterFields.Contains(x.Name)&&x.ClrType == typeof(bool))) 25 | { 26 | var parameter = Expression.Parameter(mutableEntityType.ClrType, "x"); 27 | var body = Expression.Equal(Expression.Call( 28 | typeof(EF), nameof(EF.Property), new[] {mutableProperty.ClrType}, parameter, 29 | Expression.Constant(mutableProperty.Name)), Expression.Constant(false)); 30 | modelBuilder.Entity(mutableEntityType.ClrType).HasQueryFilter(Expression.Lambda(body,parameter)); 31 | } 32 | } 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /JieDDDFramework.Data.EntityFramework/ModelConfigurations/Services/IAutoApplyConfigurationService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using Microsoft.EntityFrameworkCore; 5 | 6 | namespace JieDDDFramework.Data.EntityFramework.ModelConfigurations.Services 7 | { 8 | public interface IAutoApplyConfigurationService 9 | { 10 | void AutoApplyConfiguration(ModelBuilder modelBuilder, TDbContext dbContext) where TDbContext : Microsoft.EntityFrameworkCore.DbContext; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /JieDDDFramework.Data.EntityFramework/ModelConfigurations/Services/IFixModelConfigurationService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using Microsoft.EntityFrameworkCore; 5 | 6 | namespace JieDDDFramework.Data.EntityFramework.ModelConfigurations.Services 7 | { 8 | public interface IFixModelConfigurationService 9 | { 10 | void FixModel(ModelBuilder modelBuilder, TDbContext dbContext) where TDbContext : Microsoft.EntityFrameworkCore.DbContext; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /JieDDDFramework.Data.EntityFramework/ModelConfigurations/Services/IGlobalFilterService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using Microsoft.EntityFrameworkCore; 5 | 6 | namespace JieDDDFramework.Data.EntityFramework.ModelConfigurations.Services 7 | { 8 | public interface IGlobalFilterService 9 | { 10 | void QueryFilter(ModelBuilder modelBuilder, TDbContext dbContext) where TDbContext : Microsoft.EntityFrameworkCore.DbContext; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /JieDDDFramework.Data.EntityFramework/QueryablePageListExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | using JieDDDFramework.Core.Models; 5 | using Microsoft.EntityFrameworkCore; 6 | 7 | namespace JieDDDFramework.Data.EntityFramework 8 | { 9 | public static class QueryablePageListExtensions 10 | { 11 | public static async Task> ToPageResult(this IQueryable query, int pageIndex, int pageSize, bool findTotalCount = true, CancellationToken cancellationToken = default(CancellationToken)) 12 | { 13 | var pageResult = new PagedList(); 14 | if (findTotalCount) 15 | { 16 | var totalCount = await query.CountAsync(cancellationToken: cancellationToken).ConfigureAwait(false); 17 | var totalPages = totalCount / pageSize; 18 | pageResult.TotalPages = totalCount % pageSize == 0 ? totalPages : totalPages + 1; 19 | pageResult.TotalCount = totalCount; 20 | } 21 | 22 | pageResult.Rows = await query.Skip(pageIndex * pageSize).Take(pageSize).ToListAsync(cancellationToken: cancellationToken).ConfigureAwait(false); 23 | pageResult.PageIndex = pageIndex; 24 | pageResult.PageSize = pageSize; 25 | return pageResult; 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /JieDDDFramework.Data.EntityFramework/Repositories/Repository`1.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Data; 4 | using System.Linq; 5 | using System.Linq.Expressions; 6 | using System.Reflection; 7 | using System.Text; 8 | using System.Threading; 9 | using System.Threading.Tasks; 10 | using JieDDDFramework.Core.Domain; 11 | using JieDDDFramework.Core.Exceptions; 12 | using JieDDDFramework.Core.Exceptions.Utilities; 13 | using JieDDDFramework.Data.EntityFramework.DbContext; 14 | using JieDDDFramework.Data.Repository; 15 | using Microsoft.EntityFrameworkCore; 16 | 17 | namespace JieDDDFramework.Data.EntityFramework.Repositories 18 | { 19 | /// 20 | /// 基于EF实现的默认仓储 21 | /// 22 | /// 23 | public class Repository : IRepositoryBase where TEntity : class, IEntity 24 | { 25 | protected readonly DomainDbContext _domainDbContext; 26 | protected DbSet _entities; 27 | 28 | protected DbSet Entities => _entities ?? (_entities = _domainDbContext.Set()); 29 | 30 | public IUnitOfWork UnitOfWork => _domainDbContext; 31 | 32 | public Repository(DomainDbContext context) => _domainDbContext = context ?? throw new ArgumentException(nameof(context)); 33 | 34 | 35 | public virtual void Dispose() 36 | { 37 | // 38 | } 39 | 40 | public virtual void Insert(TEntity entity) => Entities.Add(entity); 41 | 42 | public virtual void Insert(params TEntity[] entities) => Entities.AddRange(entities); 43 | 44 | public virtual void Insert(IEnumerable entities) => Entities.AddRange(entities); 45 | 46 | public virtual Task InsertAsync(TEntity entity, CancellationToken cancellationToken = default(CancellationToken)) => Entities.AddAsync(entity, cancellationToken); 47 | 48 | public virtual Task InsertAsync(params TEntity[] entities) => Entities.AddRangeAsync(entities); 49 | 50 | public virtual Task InsertAsync(IEnumerable entities, 51 | CancellationToken cancellationToken = default(CancellationToken)) => 52 | Entities.AddRangeAsync(entities, cancellationToken); 53 | 54 | public virtual void Update(TEntity entity) => Entities.Update(entity); 55 | 56 | public virtual void Update(params TEntity[] entities) => Entities.UpdateRange(entities); 57 | public virtual void Update(IEnumerable entities) => Entities.UpdateRange(entities); 58 | 59 | public virtual void Delete(object id) 60 | { 61 | var typeInfo = typeof(TEntity).GetTypeInfo(); 62 | var key = _domainDbContext.Model.FindEntityType(typeInfo).FindPrimaryKey().Properties.FirstOrDefault(); 63 | var property = typeInfo.GetProperty(key?.Name); 64 | if (property != null) 65 | { 66 | var entity = Activator.CreateInstance(); 67 | property.SetValue(entity, id); 68 | _domainDbContext.Entry(entity).State = EntityState.Deleted; 69 | } 70 | else 71 | { 72 | var entity = Entities.Find(id); 73 | if (entity != null) 74 | { 75 | Delete(entity); 76 | } 77 | } 78 | } 79 | 80 | public virtual void Delete(TEntity entity) => Entities.Remove(entity); 81 | 82 | public virtual void Delete(params TEntity[] entities) => Entities.RemoveRange(entities); 83 | 84 | public virtual void Delete(IEnumerable entities) => Entities.RemoveRange(entities); 85 | 86 | public TEntity FindEntity(object keyValue) 87 | { 88 | var entity = Entities.Find(keyValue); 89 | if (entity == null || entity is IAggregateRoot) 90 | { 91 | return entity; 92 | } 93 | throw new DomainException("Entity must implement IAggregateRoot"); 94 | } 95 | 96 | public virtual TEntity FindEntity(Expression> criterion) 97 | { 98 | var entity = Entities.SingleOrDefault(criterion); 99 | if (entity == null || entity is IAggregateRoot) 100 | { 101 | return entity; 102 | } 103 | throw new DomainException("Entity must implement IAggregateRoot"); 104 | } 105 | 106 | public virtual async Task FindEntityAsync(object keyValue) 107 | { 108 | var entity = await Entities.FindAsync(keyValue); 109 | if (entity ==null || entity is IAggregateRoot) 110 | { 111 | return entity; 112 | } 113 | throw new DomainException("Entity must implement IAggregateRoot"); 114 | } 115 | 116 | public virtual async Task FindEntityAsync(Expression> criterion) 117 | { 118 | 119 | var entity = await Entities.SingleOrDefaultAsync(criterion); 120 | if (entity == null || entity is IAggregateRoot) 121 | { 122 | return entity; 123 | } 124 | throw new DomainException("Entity must implement IAggregateRoot"); 125 | } 126 | 127 | public virtual IQueryable Tables() => Entities.AsNoTracking(); 128 | 129 | public virtual IQueryable Tables(Expression> criterion) => Entities.AsNoTracking().Where(criterion); 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /JieDDDFramework.Data.EntityFramework/RepositoryExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using JieDDDFramework.Data.EntityFramework.DbContext; 5 | using JieDDDFramework.Data.EntityFramework.Repositories; 6 | using JieDDDFramework.Data.Repository; 7 | using Microsoft.Extensions.DependencyInjection; 8 | 9 | namespace JieDDDFramework.Data.EntityFramework 10 | { 11 | public static class RepositoryExtensions 12 | { 13 | public static IServiceCollection AddRepository(this IServiceCollection services) where TDbContext : DomainDbContext 14 | { 15 | services.AddScoped(); 16 | services.AddTransient(typeof(IRepositoryBase<>), typeof(Repository<>)); 17 | return services; 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /JieDDDFramework.Data/JieDDDFramework.Data.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /JieDDDFramework.Data/Repository/IRepositoryBase`1.cs: -------------------------------------------------------------------------------- 1 | //using System; 2 | 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Linq.Expressions; 7 | using System.Text; 8 | using System.Threading; 9 | using System.Threading.Tasks; 10 | using JieDDDFramework.Core.Domain; 11 | 12 | namespace JieDDDFramework.Data.Repository 13 | { 14 | public interface IRepositoryBase : IDisposable where TEntity : IEntity 15 | { 16 | IUnitOfWork UnitOfWork { get; } 17 | 18 | void Insert(TEntity entity); 19 | 20 | void Insert(params TEntity[] entities); 21 | 22 | void Insert(IEnumerable entities); 23 | 24 | Task InsertAsync(TEntity entity, CancellationToken cancellationToken = default(CancellationToken)); 25 | 26 | Task InsertAsync(params TEntity[] entities); 27 | 28 | Task InsertAsync(IEnumerable entities, CancellationToken cancellationToken = default(CancellationToken)); 29 | /// 30 | /// Updates the specified entity. 31 | /// 32 | /// The entity. 33 | void Update(TEntity entity); 34 | 35 | /// 36 | /// Updates the specified entities. 37 | /// 38 | /// The entities. 39 | void Update(params TEntity[] entities); 40 | 41 | /// 42 | /// Updates the specified entities. 43 | /// 44 | /// The entities. 45 | void Update(IEnumerable entities); 46 | 47 | /// 48 | /// Deletes the entity by the specified primary key. 49 | /// 50 | /// The primary key value. 51 | void Delete(object id); 52 | 53 | /// 54 | /// Deletes the specified entity. 55 | /// 56 | /// The entity to delete. 57 | void Delete(TEntity entity); 58 | 59 | /// 60 | /// Deletes the specified entities. 61 | /// 62 | /// The entities. 63 | void Delete(params TEntity[] entities); 64 | 65 | /// 66 | /// Deletes the specified entities. 67 | /// 68 | /// The entities. 69 | void Delete(IEnumerable entities); 70 | 71 | /// 72 | /// 返回领域根对象 73 | /// 不为IAggregateRoot时 74 | /// 75 | /// 76 | /// 77 | TEntity FindEntity(object keyValue); 78 | 79 | /// 80 | /// 返回领域根对象 81 | /// 不为IAggregateRoot时 82 | /// 83 | /// 84 | /// 85 | TEntity FindEntity(Expression> criterion); 86 | 87 | /// 88 | /// 返回领域根对象 89 | /// 不为IAggregateRoot时 90 | /// 91 | /// 92 | /// 93 | Task FindEntityAsync(object keyValue); 94 | 95 | /// 96 | /// 返回领域根对象 97 | /// 不为IAggregateRoot时 98 | /// 99 | /// 100 | /// 101 | Task FindEntityAsync(Expression> criterion); 102 | IQueryable Tables(); 103 | 104 | IQueryable Tables(Expression> criterion); 105 | 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /JieDDDFramework.Service/Dtos/IDto.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace JieDDDFramework.Service.Dtos 6 | { 7 | /// 8 | /// 数据传输对象 9 | /// 10 | public interface IDto:IRequest, IResponse 11 | { 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /JieDDDFramework.Service/Dtos/IRequest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace JieDDDFramework.Service.Dtos 6 | { 7 | /// 8 | /// 请求参数 9 | /// 10 | public interface IRequest 11 | { 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /JieDDDFramework.Service/Dtos/IResponse.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace JieDDDFramework.Service.Dtos 6 | { 7 | /// 8 | /// 响应结果 9 | /// 10 | public interface IResponse 11 | { 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /JieDDDFramework.Service/IQueryService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using JieDDDFramework.Core.Models; 5 | using JieDDDFramework.Service.Dtos; 6 | using JieDDDFramework.Service.Operations; 7 | 8 | namespace JieDDDFramework.Service 9 | { 10 | /// 11 | /// 查询服务 12 | /// 13 | /// 数据传输对象类型 14 | /// 查询参数类型 15 | public interface IQueryService : IService, 16 | IGetById, IGetByIdAsync, 17 | IGetAll, IGetAllAsync, 18 | IPageQuery, IPageQueryAsync 19 | where TDto : IResponse, new() 20 | where TQueryParameter : IPagerQueryParameter 21 | { 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /JieDDDFramework.Service/IService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace JieDDDFramework.Service 6 | { 7 | /// 8 | /// 应用服务 9 | /// 10 | public interface IService 11 | { 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /JieDDDFramework.Service/JieDDDFramework.Service.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /JieDDDFramework.Service/Operations/IGetAll.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using JieDDDFramework.Service.Dtos; 5 | 6 | namespace JieDDDFramework.Service.Operations 7 | { 8 | /// 9 | /// 获取全部数据 10 | /// 11 | public interface IGetAll where TDto : IResponse, new() 12 | { 13 | /// 14 | /// 获取全部 15 | /// 16 | List GetAll(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /JieDDDFramework.Service/Operations/IGetAllAsync.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | using JieDDDFramework.Service.Dtos; 6 | 7 | namespace JieDDDFramework.Service.Operations 8 | { 9 | /// 10 | /// 获取全部数据 11 | /// 12 | public interface IGetAllAsync where TDto : IResponse, new() 13 | { 14 | /// 15 | /// 获取全部 16 | /// 17 | Task> GetAllAsync(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /JieDDDFramework.Service/Operations/IGetById.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using JieDDDFramework.Service.Dtos; 5 | 6 | namespace JieDDDFramework.Service.Operations 7 | { 8 | /// 9 | /// 获取指定标识实体 10 | /// 11 | public interface IGetById where TDto : IResponse, new() 12 | { 13 | /// 14 | /// 通过编号获取 15 | /// 16 | /// 实体编号 17 | TDto GetById(object id); 18 | /// 19 | /// 通过编号列表获取 20 | /// 21 | List GetByIds(List ids); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /JieDDDFramework.Service/Operations/IGetByIdAsync.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | using JieDDDFramework.Service.Dtos; 6 | 7 | namespace JieDDDFramework.Service.Operations 8 | { 9 | /// 10 | /// 获取指定标识实体 11 | /// 12 | public interface IGetByIdAsync where TDto : IResponse, new() 13 | { 14 | /// 15 | /// 通过编号获取 16 | /// 17 | /// 实体编号 18 | Task GetByIdAsync(object id); 19 | /// 20 | /// 通过编号列表获取 21 | /// 22 | Task> GetByIdsAsync(List ids); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /JieDDDFramework.Service/Operations/IPageQuery.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using JieDDDFramework.Core.Models; 5 | using JieDDDFramework.Service.Dtos; 6 | 7 | namespace JieDDDFramework.Service.Operations 8 | { 9 | /// 10 | /// 分页查询 11 | /// 12 | /// 数据传输对象类型 13 | /// 查询参数类型 14 | public interface IPageQuery 15 | where TDto : IResponse, new() 16 | where TQueryParameter : IPagerQueryParameter 17 | { 18 | /// 19 | /// 查询 20 | /// 21 | /// 查询参数 22 | List Query(TQueryParameter parameter); 23 | /// 24 | /// 分页查询 25 | /// 26 | /// 查询参数 27 | IPagedList PagerQuery(TQueryParameter parameter); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /JieDDDFramework.Service/Operations/IPageQueryAsync.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | using JieDDDFramework.Core.Models; 6 | using JieDDDFramework.Service.Dtos; 7 | 8 | namespace JieDDDFramework.Service.Operations 9 | { 10 | /// 11 | /// 分页查询 12 | /// 13 | /// 数据传输对象类型 14 | /// 查询参数类型 15 | public interface IPageQueryAsync 16 | where TDto : IResponse, new() 17 | where TQueryParameter : IPagerQueryParameter 18 | { 19 | /// 20 | /// 查询 21 | /// 22 | /// 查询参数 23 | Task> QueryAsync(TQueryParameter parameter); 24 | /// 25 | /// 分页查询 26 | /// 27 | /// 查询参数 28 | Task> PagerQueryAsync(TQueryParameter parameter); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /JieDDDFramework.Web/BaseController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using JieDDDFramework.Core.Models; 5 | using Microsoft.AspNetCore.Mvc; 6 | 7 | namespace JieDDDFramework.Web 8 | { 9 | public class BaseController : Controller 10 | { 11 | [NonAction] 12 | protected virtual IActionResult Success(string message = "") 13 | { 14 | var result = new ApiResult 15 | { 16 | Message = message 17 | }; 18 | result.Succeed(); 19 | return Ok(result); 20 | } 21 | 22 | [NonAction] 23 | protected virtual IActionResult Fail(string message = "",int code = -1) 24 | { 25 | var result = new ApiResult 26 | { 27 | Message = message, 28 | Code = code 29 | }; 30 | result.Fail(); 31 | return Ok(result); 32 | } 33 | 34 | [NonAction] 35 | protected virtual IActionResult Success(object data, string message = "") 36 | { 37 | var result = new ApiResult 38 | { 39 | Value = data, 40 | Message = message 41 | }; 42 | result.Succeed(); 43 | return Ok(result); 44 | } 45 | 46 | [NonAction] 47 | protected virtual IActionResult Error(string message,int code =-1) 48 | { 49 | var result = new ApiResult 50 | { 51 | Message = message, 52 | Code = -1 53 | }; 54 | result.Succeed(); 55 | return Ok(result); 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /JieDDDFramework.Web/Filters/HttpGlobalExceptionFilter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Net; 5 | using System.Text; 6 | using FluentValidation; 7 | using JieDDDFramework.Core.Exceptions; 8 | using JieDDDFramework.Core.Models; 9 | using Microsoft.AspNetCore.Hosting; 10 | using Microsoft.AspNetCore.Mvc; 11 | using Microsoft.AspNetCore.Mvc.Filters; 12 | using Microsoft.Extensions.Logging; 13 | 14 | namespace JieDDDFramework.Web.Filters 15 | { 16 | public partial class HttpGlobalExceptionFilter : IExceptionFilter 17 | { 18 | private readonly IHostingEnvironment _env; 19 | private readonly ILogger _logger; 20 | 21 | public HttpGlobalExceptionFilter(IHostingEnvironment env, ILogger logger) 22 | { 23 | this._env = env; 24 | this._logger = logger; 25 | } 26 | 27 | public void OnException(ExceptionContext context) 28 | { 29 | _logger.LogError(new EventId(context.Exception.HResult), 30 | context.Exception, 31 | context.Exception.Message); 32 | 33 | if (context.Exception is KnownException knownException) 34 | { 35 | var result = new ApiResult() 36 | { 37 | Success = false, 38 | Code = knownException.ErrorCode, 39 | Message = knownException.Message 40 | }; 41 | if (knownException.InnerException is ValidationException validationException) 42 | { 43 | var errorInfo = validationException.Errors.FirstOrDefault(); 44 | if (errorInfo!=null) 45 | { 46 | if (int.TryParse(errorInfo.ErrorCode,out var errorCode)) 47 | { 48 | result.Code = errorCode; 49 | } 50 | result.Message = errorInfo.ErrorMessage; 51 | } 52 | } 53 | context.Result = new BadRequestObjectResult(result); 54 | } 55 | else 56 | { 57 | var result = new ApiResult() 58 | { 59 | Success = false, 60 | Code = -500, 61 | Message = "An error occurred. Try it again." 62 | }; 63 | 64 | if (_env.IsDevelopment()) 65 | { 66 | result.Message = context.Exception.GetAllMessages(); 67 | } 68 | 69 | context.Result = new ObjectResult(result) 70 | { 71 | StatusCode = (int) HttpStatusCode.InternalServerError 72 | }; 73 | } 74 | context.ExceptionHandled = true; 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /JieDDDFramework.Web/Filters/MvcFilterExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using FluentValidation.AspNetCore; 6 | using FluentValidation.Results; 7 | using JieDDDFramework.Web.Models; 8 | using JieDDDFramework.Web.ModelValidate; 9 | using Microsoft.AspNetCore.Http; 10 | using Microsoft.AspNetCore.Mvc; 11 | using Microsoft.Extensions.DependencyInjection; 12 | 13 | namespace JieDDDFramework.Web.Filters 14 | { 15 | public static class MvcFilterExtensions 16 | { 17 | public static IMvcBuilder AddCustomFilter(this IMvcBuilder builder) 18 | { 19 | //builder.Services.AddScoped(); 20 | builder.Services.AddScoped(); 21 | builder.AddMvcOptions(x => 22 | { 23 | //x.Filters.AddService(); 24 | x.Filters.AddService(); 25 | }); 26 | builder.Services.Configure(options => 27 | { 28 | options.InvalidModelStateResponseFactory = context => 29 | { 30 | if (context.HttpContext.Items.TryGetValue(ValidatorAttribute.VALIDATOR_ITEM, out var obj)) 31 | { 32 | if (obj is IList validationFailures && validationFailures.Any()) 33 | { 34 | return new BadRequestObjectResult(new ModelErrorResult(validationFailures.First())); 35 | } 36 | } 37 | return null; 38 | }; 39 | }); 40 | return builder; 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /JieDDDFramework.Web/Filters/ValidateModelStateFilter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using FluentValidation.Results; 5 | using JieDDDFramework.Web.Models; 6 | using JieDDDFramework.Web.ModelValidate; 7 | using Microsoft.AspNetCore.Mvc; 8 | using Microsoft.AspNetCore.Mvc.Filters; 9 | using Microsoft.AspNetCore.Mvc.ModelBinding; 10 | using Newtonsoft.Json; 11 | 12 | namespace JieDDDFramework.Web.Filters 13 | { 14 | public class ValidateModelStateFilter : IActionFilter 15 | { 16 | public void OnActionExecuting(ActionExecutingContext context) 17 | { 18 | if (context.ModelState.IsValid) 19 | { 20 | return; 21 | } 22 | if (context.HttpContext.Items.TryGetValue(ValidatorAttribute.VALIDATOR_ITEM, out var obj)) 23 | { 24 | if (obj is IList validationFailures&& validationFailures.Any()) 25 | { 26 | context.Result = new BadRequestObjectResult(new ModelErrorResult(validationFailures.First())); 27 | return; 28 | } 29 | } 30 | 31 | var result = new ModelErrorResult(context.ModelState); 32 | context.Result = new BadRequestObjectResult(result); 33 | } 34 | 35 | public void OnActionExecuted(ActionExecutedContext context) 36 | { 37 | 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /JieDDDFramework.Web/JieDDDFramework.Web.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /JieDDDFramework.Web/ModelValidate/ModelResultValidatorInterceptor.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using FluentValidation; 6 | using FluentValidation.AspNetCore; 7 | using FluentValidation.Results; 8 | using JieDDDFramework.Web.Models; 9 | using Microsoft.AspNetCore.Mvc; 10 | using Microsoft.AspNetCore.Mvc.Infrastructure; 11 | using Microsoft.Extensions.DependencyInjection; 12 | using Newtonsoft.Json; 13 | 14 | namespace JieDDDFramework.Web.ModelValidate 15 | { 16 | public class ModelResultValidatorInterceptor: IValidatorInterceptor 17 | { 18 | public ValidationContext BeforeMvcValidation(ControllerContext controllerContext, ValidationContext validationContext) 19 | { 20 | return validationContext; 21 | } 22 | 23 | public ValidationResult AfterMvcValidation(ControllerContext controllerContext, ValidationContext validationContext, 24 | ValidationResult result) 25 | { 26 | if (result.IsValid) 27 | { 28 | return result; 29 | } 30 | controllerContext.HttpContext.Items[ValidatorAttribute.VALIDATOR_ITEM] = result.Errors; 31 | return result; 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /JieDDDFramework.Web/ModelValidate/ValidatorAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using FluentValidation.AspNetCore; 5 | 6 | namespace JieDDDFramework.Web.ModelValidate 7 | { 8 | public class ValidatorAttribute : CustomizeValidatorAttribute 9 | { 10 | public const string VALIDATOR_ITEM= "VALIDATOR_ITEM"; 11 | public ValidatorAttribute() 12 | { 13 | Interceptor = typeof(ModelResultValidatorInterceptor); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /JieDDDFramework.Web/Models/ModelErrorResult.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using FluentValidation.Results; 4 | using JieDDDFramework.Core.Models; 5 | using Microsoft.AspNetCore.Mvc.ModelBinding; 6 | 7 | namespace JieDDDFramework.Web.Models 8 | { 9 | public class ModelErrorResult : ApiResult 10 | { 11 | public ModelErrorResult() 12 | { 13 | 14 | } 15 | public ModelErrorResult(ModelStateDictionary modelStateDictionary) 16 | { 17 | Success = false; 18 | Code = -1; 19 | Message = modelStateDictionary.Keys.SelectMany(x=>modelStateDictionary[x].Errors) 20 | .Select(x=>x.ErrorMessage) 21 | .FirstOrDefault(); 22 | } 23 | 24 | public ModelErrorResult(ValidationFailure validationFailure) 25 | { 26 | Success = false; 27 | Code = -1; 28 | if (int.TryParse(validationFailure.ErrorCode, out var errorCode)) 29 | { 30 | Code = errorCode; 31 | } 32 | Message = validationFailure.ErrorMessage; 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /JieDDDFramework.Web/Models/PagedCriteria.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel.DataAnnotations; 4 | using System.Text; 5 | using JieDDDFramework.Core.Models; 6 | using Microsoft.CodeAnalysis.CSharp.Syntax; 7 | 8 | namespace JieDDDFramework.Web.Models 9 | { 10 | public class PagedCriteria : IPagerQueryParameter 11 | { 12 | public PagedCriteria() 13 | { 14 | } 15 | public int PageIndex { get; set; } 16 | 17 | public int PageSize { get; set; } = 50; 18 | 19 | public int PageNumber => PageIndex + 1; 20 | 21 | public List OrderSorts { get; set; } 22 | } 23 | 24 | 25 | } 26 | -------------------------------------------------------------------------------- /JieDDDFramework.Web/Validate/FluentValidationExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Reflection; 4 | using System.Text; 5 | using FluentValidation; 6 | using FluentValidation.AspNetCore; 7 | using JieDDDFramework.Web.Models; 8 | using JieDDDFramework.Web.ModelValidate; 9 | using Microsoft.Extensions.DependencyInjection; 10 | 11 | namespace JieDDDFramework.Web.Validate 12 | { 13 | public static class FluentValidationExtensions 14 | { 15 | public static IMvcBuilder AddCustomFluentValidation(this IMvcBuilder builder, 16 | Action configurationExpression = null) 17 | { 18 | builder.Services.AddTransient, PagedCriteriaValidator>(); 19 | var executingAssembly = Assembly.GetExecutingAssembly(); 20 | if (configurationExpression == null) 21 | { 22 | configurationExpression = x => x.RegisterValidatorsFromAssembly(executingAssembly); 23 | } 24 | 25 | builder.AddFluentValidation(configurationExpression); 26 | return builder; 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /JieDDDFramework.Web/Validate/PagedCriteriaValidator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using FluentValidation; 5 | using JieDDDFramework.Web.Models; 6 | 7 | namespace JieDDDFramework.Web.Validate 8 | { 9 | public class PagedCriteriaValidator : AbstractValidator 10 | { 11 | public PagedCriteriaValidator() 12 | { 13 | RuleFor(x => x.PageIndex).GreaterThanOrEqualTo(0).WithMessage("PagedIndex必须大于等于0"); 14 | RuleFor(x=>x.PageSize).GreaterThan(0).WithMessage("PageSize必须大于0"); 15 | RuleForEach(x => x.OrderSorts).Must(x => x.OrderType >= 0 && (uint) x.OrderType <= 1) 16 | .WithMessage("OrderType无效"); 17 | 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /JieDDDFramework.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.28307.106 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JieDDDFramework.Core", "JieDDDFramework.Core\JieDDDFramework.Core.csproj", "{FF328A32-979C-45BC-98D1-DAB2669FEAB9}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JieDDDFramework.Data", "JieDDDFramework.Data\JieDDDFramework.Data.csproj", "{C2656CA2-4B23-4BE1-A2FE-3CABA8C748AA}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JieDDDFramework.Data.EntityFramework", "JieDDDFramework.Data.EntityFramework\JieDDDFramework.Data.EntityFramework.csproj", "{18D1173F-E777-48A9-B885-D07908F34775}" 11 | EndProject 12 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Example", "Example", "{7BCE3166-E9BC-4F67-BAAB-E5C3468FE41F}" 13 | EndProject 14 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Module", "Module", "{5DC72A69-71F4-499E-81E9-935CD1E2E3DA}" 15 | EndProject 16 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JieDDDFramework.Module.Identity", "Module\JieDDDFramework.Module.Identity\JieDDDFramework.Module.Identity.csproj", "{CE0D234A-4903-472D-A492-B5F1C717FD45}" 17 | EndProject 18 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Identity.API", "Example\Identity.API\Identity.API.csproj", "{B640DCDB-6470-4B01-8A56-1D8C83AE1707}" 19 | EndProject 20 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JieDDDFramework.Web", "JieDDDFramework.Web\JieDDDFramework.Web.csproj", "{DB4BE020-FFDE-4A40-A832-9A44D128F942}" 21 | EndProject 22 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Order.Domain", "Example\Order.Domain\Order.Domain.csproj", "{D7B5DAC6-7AE3-486F-ADBC-34EDE25E6312}" 23 | EndProject 24 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Order.API", "Example\Order.API\Order.API.csproj", "{482C46C6-D8E8-44F3-9104-92D7D2F87AE1}" 25 | EndProject 26 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JieDDDFramework.Service", "JieDDDFramework.Service\JieDDDFramework.Service.csproj", "{14188F58-00DE-4703-9987-BC90AFB7C59E}" 27 | EndProject 28 | Global 29 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 30 | Debug|Any CPU = Debug|Any CPU 31 | Release|Any CPU = Release|Any CPU 32 | EndGlobalSection 33 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 34 | {FF328A32-979C-45BC-98D1-DAB2669FEAB9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 35 | {FF328A32-979C-45BC-98D1-DAB2669FEAB9}.Debug|Any CPU.Build.0 = Debug|Any CPU 36 | {FF328A32-979C-45BC-98D1-DAB2669FEAB9}.Release|Any CPU.ActiveCfg = Release|Any CPU 37 | {FF328A32-979C-45BC-98D1-DAB2669FEAB9}.Release|Any CPU.Build.0 = Release|Any CPU 38 | {C2656CA2-4B23-4BE1-A2FE-3CABA8C748AA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 39 | {C2656CA2-4B23-4BE1-A2FE-3CABA8C748AA}.Debug|Any CPU.Build.0 = Debug|Any CPU 40 | {C2656CA2-4B23-4BE1-A2FE-3CABA8C748AA}.Release|Any CPU.ActiveCfg = Release|Any CPU 41 | {C2656CA2-4B23-4BE1-A2FE-3CABA8C748AA}.Release|Any CPU.Build.0 = Release|Any CPU 42 | {18D1173F-E777-48A9-B885-D07908F34775}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 43 | {18D1173F-E777-48A9-B885-D07908F34775}.Debug|Any CPU.Build.0 = Debug|Any CPU 44 | {18D1173F-E777-48A9-B885-D07908F34775}.Release|Any CPU.ActiveCfg = Release|Any CPU 45 | {18D1173F-E777-48A9-B885-D07908F34775}.Release|Any CPU.Build.0 = Release|Any CPU 46 | {CE0D234A-4903-472D-A492-B5F1C717FD45}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 47 | {CE0D234A-4903-472D-A492-B5F1C717FD45}.Debug|Any CPU.Build.0 = Debug|Any CPU 48 | {CE0D234A-4903-472D-A492-B5F1C717FD45}.Release|Any CPU.ActiveCfg = Release|Any CPU 49 | {CE0D234A-4903-472D-A492-B5F1C717FD45}.Release|Any CPU.Build.0 = Release|Any CPU 50 | {B640DCDB-6470-4B01-8A56-1D8C83AE1707}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 51 | {B640DCDB-6470-4B01-8A56-1D8C83AE1707}.Debug|Any CPU.Build.0 = Debug|Any CPU 52 | {B640DCDB-6470-4B01-8A56-1D8C83AE1707}.Release|Any CPU.ActiveCfg = Release|Any CPU 53 | {B640DCDB-6470-4B01-8A56-1D8C83AE1707}.Release|Any CPU.Build.0 = Release|Any CPU 54 | {DB4BE020-FFDE-4A40-A832-9A44D128F942}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 55 | {DB4BE020-FFDE-4A40-A832-9A44D128F942}.Debug|Any CPU.Build.0 = Debug|Any CPU 56 | {DB4BE020-FFDE-4A40-A832-9A44D128F942}.Release|Any CPU.ActiveCfg = Release|Any CPU 57 | {DB4BE020-FFDE-4A40-A832-9A44D128F942}.Release|Any CPU.Build.0 = Release|Any CPU 58 | {D7B5DAC6-7AE3-486F-ADBC-34EDE25E6312}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 59 | {D7B5DAC6-7AE3-486F-ADBC-34EDE25E6312}.Debug|Any CPU.Build.0 = Debug|Any CPU 60 | {D7B5DAC6-7AE3-486F-ADBC-34EDE25E6312}.Release|Any CPU.ActiveCfg = Release|Any CPU 61 | {D7B5DAC6-7AE3-486F-ADBC-34EDE25E6312}.Release|Any CPU.Build.0 = Release|Any CPU 62 | {482C46C6-D8E8-44F3-9104-92D7D2F87AE1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 63 | {482C46C6-D8E8-44F3-9104-92D7D2F87AE1}.Debug|Any CPU.Build.0 = Debug|Any CPU 64 | {482C46C6-D8E8-44F3-9104-92D7D2F87AE1}.Release|Any CPU.ActiveCfg = Release|Any CPU 65 | {482C46C6-D8E8-44F3-9104-92D7D2F87AE1}.Release|Any CPU.Build.0 = Release|Any CPU 66 | {14188F58-00DE-4703-9987-BC90AFB7C59E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 67 | {14188F58-00DE-4703-9987-BC90AFB7C59E}.Debug|Any CPU.Build.0 = Debug|Any CPU 68 | {14188F58-00DE-4703-9987-BC90AFB7C59E}.Release|Any CPU.ActiveCfg = Release|Any CPU 69 | {14188F58-00DE-4703-9987-BC90AFB7C59E}.Release|Any CPU.Build.0 = Release|Any CPU 70 | EndGlobalSection 71 | GlobalSection(SolutionProperties) = preSolution 72 | HideSolutionNode = FALSE 73 | EndGlobalSection 74 | GlobalSection(NestedProjects) = preSolution 75 | {CE0D234A-4903-472D-A492-B5F1C717FD45} = {5DC72A69-71F4-499E-81E9-935CD1E2E3DA} 76 | {B640DCDB-6470-4B01-8A56-1D8C83AE1707} = {7BCE3166-E9BC-4F67-BAAB-E5C3468FE41F} 77 | {D7B5DAC6-7AE3-486F-ADBC-34EDE25E6312} = {7BCE3166-E9BC-4F67-BAAB-E5C3468FE41F} 78 | {482C46C6-D8E8-44F3-9104-92D7D2F87AE1} = {7BCE3166-E9BC-4F67-BAAB-E5C3468FE41F} 79 | EndGlobalSection 80 | GlobalSection(ExtensibilityGlobals) = postSolution 81 | SolutionGuid = {BA329D25-2C6E-4797-A174-5086A73ED416} 82 | EndGlobalSection 83 | EndGlobal 84 | -------------------------------------------------------------------------------- /Module/JieDDDFramework.Module.Identity/Data/IdentityUserDbContext.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using JieDDDFramework.Module.Identity.Models; 3 | using Microsoft.AspNetCore.Identity; 4 | using Microsoft.AspNetCore.Identity.EntityFrameworkCore; 5 | using Microsoft.EntityFrameworkCore; 6 | 7 | namespace JieDDDFramework.Module.Identity.Data 8 | { 9 | public class IdentityUserDbContext : IdentityDbContext 10 | { 11 | public IdentityUserDbContext(DbContextOptions options) : base(options) 12 | { 13 | } 14 | 15 | public void OnModelCreating1(ModelBuilder builder) 16 | { 17 | 18 | } 19 | 20 | protected override void OnModelCreating(ModelBuilder builder) 21 | { 22 | base.OnModelCreating(builder); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Module/JieDDDFramework.Module.Identity/IdentityServerExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using IdentityServer4.AspNetIdentity; 3 | using IdentityServer4.Configuration; 4 | using IdentityServer4.EntityFramework.Options; 5 | using IdentityServer4.Services; 6 | using JieDDDFramework.Module.Identity.Models; 7 | using Microsoft.EntityFrameworkCore; 8 | using Microsoft.Extensions.DependencyInjection; 9 | 10 | namespace JieDDDFramework.Module.Identity 11 | { 12 | public static class IdentityServerExtensions 13 | { 14 | public static IIdentityServerBuilder AddDefaultIdentityServerConfig(this IIdentityServerBuilder builder,Action dbContextOptionsBuilder = null) where TApplicationUser : ApplicationUser 15 | { 16 | builder.AddAspNetIdentity() 17 | .AddConfigurationStore(options => options.ConfigureDbContext = dbContextOptionsBuilder) 18 | .AddOperationalStore(options => options.ConfigureDbContext = dbContextOptionsBuilder) 19 | .Services.AddTransient>(); ; 20 | return builder; 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Module/JieDDDFramework.Module.Identity/JieDDDFramework.Module.Identity.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /Module/JieDDDFramework.Module.Identity/JwtSettings.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace JieDDDFramework.Module.Identity 6 | { 7 | public class JwtSettings 8 | { 9 | public string Issuer { get; set; } 10 | public string Audience { get; set; } 11 | public string SecretKey { get; set; } 12 | public string ClientId { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Module/JieDDDFramework.Module.Identity/Models/ApplicationUser.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel.DataAnnotations; 3 | using Microsoft.AspNetCore.Identity; 4 | 5 | namespace JieDDDFramework.Module.Identity.Models 6 | { 7 | public class ApplicationUser : IdentityUser 8 | { 9 | [Required] 10 | public string City { get; set; } 11 | [Required] 12 | public string State { get; set; } 13 | [Required] 14 | public string Country { get; set; } 15 | [Required] 16 | public string Name { get; set; } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Module/JieDDDFramework.Module.Identity/Services/ILoginService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading.Tasks; 3 | 4 | namespace JieDDDFramework.Module.Identity.Services 5 | { 6 | public interface ILoginService 7 | { 8 | Task ValidateCredentials(T user, string password); 9 | Task FindByUsername(string user); 10 | Task SignIn(T user); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Module/JieDDDFramework.Module.Identity/Services/IRedirectService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | namespace JieDDDFramework.Module.Identity.Services 3 | { 4 | public interface IRedirectService 5 | { 6 | string ExtractRedirectUriFromReturnUrl(string url); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Module/JieDDDFramework.Module.Identity/Services/IdentityLoginService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text.RegularExpressions; 3 | using System.Threading.Tasks; 4 | using JieDDDFramework.Module.Identity.Models; 5 | using Microsoft.AspNetCore.Identity; 6 | 7 | namespace JieDDDFramework.Module.Identity.Services 8 | { 9 | public class IdentityLoginService : ILoginService where TApplicationUser : ApplicationUser 10 | { 11 | private UserManager _userManager; 12 | private SignInManager _signInManager; 13 | 14 | public IdentityLoginService(UserManager userManager,SignInManager signInManager) 15 | { 16 | _userManager = userManager; 17 | _signInManager = signInManager; 18 | } 19 | 20 | public async Task FindByUsername(string account) 21 | { 22 | TApplicationUser user = null; 23 | if (Regex.IsMatch(account, @"^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$", RegexOptions.IgnoreCase)) 24 | { 25 | user = await _userManager.FindByEmailAsync(account); 26 | } 27 | if (user == null) 28 | { 29 | user = await _userManager.FindByNameAsync(account); 30 | } 31 | return user; 32 | } 33 | 34 | public Task SignIn(TApplicationUser user) 35 | { 36 | return _signInManager.SignInAsync(user,true); 37 | } 38 | 39 | public Task ValidateCredentials(TApplicationUser user, string password) 40 | { 41 | return _userManager.CheckPasswordAsync(user, password); 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Module/JieDDDFramework.Module.Identity/Services/ProfileService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Security.Claims; 5 | using System.Threading.Tasks; 6 | using IdentityModel; 7 | using IdentityServer4.Models; 8 | using IdentityServer4.Services; 9 | using JieDDDFramework.Module.Identity.Models; 10 | using Microsoft.AspNetCore.Identity; 11 | 12 | namespace JieDDDFramework.Module.Identity.Services 13 | { 14 | public class ProfileService : IProfileService where TApplicationUser:ApplicationUser 15 | { 16 | private readonly UserManager _userManager; 17 | 18 | public ProfileService(UserManager userManager) 19 | { 20 | _userManager = userManager; 21 | } 22 | 23 | public virtual async Task GetProfileDataAsync(ProfileDataRequestContext context) 24 | { 25 | var subject = context.Subject ?? throw new ArgumentNullException(nameof(context.Subject)); 26 | var subjectId = subject.Claims?.First(x => x.Type == "sub"); 27 | var user = await _userManager.FindByIdAsync(subjectId.Value); 28 | if (user == null) 29 | throw new ArgumentException("Invalid subject identifier"); 30 | var claims = GetClaimsFromUser(user); 31 | context.IssuedClaims = claims.ToList(); 32 | } 33 | 34 | public virtual async Task IsActiveAsync(IsActiveContext context) 35 | { 36 | var subject = context.Subject ?? throw new ArgumentNullException(nameof(context.Subject)); 37 | 38 | var subjectId = subject.Claims?.First(x => x.Type == "sub"); 39 | var user = await _userManager.FindByIdAsync(subjectId.Value); 40 | 41 | context.IsActive = false; 42 | 43 | if (user != null) 44 | { 45 | if (_userManager.SupportsUserSecurityStamp) 46 | { 47 | var security_stamp = subject.Claims.Where(c => c.Type == "security_stamp").Select(c => c.Value).SingleOrDefault(); 48 | if (security_stamp != null) 49 | { 50 | var db_security_stamp = await _userManager.GetSecurityStampAsync(user); 51 | if (db_security_stamp != security_stamp) 52 | return; 53 | } 54 | } 55 | 56 | context.IsActive = 57 | !user.LockoutEnabled || 58 | !user.LockoutEnd.HasValue || 59 | user.LockoutEnd <= DateTime.Now; 60 | } 61 | } 62 | 63 | public virtual IEnumerable GetClaimsFromUser(TApplicationUser user) 64 | { 65 | var claims = new List 66 | { 67 | new Claim(JwtClaimTypes.Subject, user.Id), 68 | new Claim(JwtClaimTypes.PreferredUserName, user.UserName) 69 | }; 70 | if (!string.IsNullOrWhiteSpace(user.Name)) 71 | claims.Add(new Claim("name", user.Name)); 72 | 73 | if (!string.IsNullOrWhiteSpace(user.City)) 74 | claims.Add(new Claim("address_city", user.City)); 75 | 76 | if (!string.IsNullOrWhiteSpace(user.Country)) 77 | claims.Add(new Claim("address_country", user.Country)); 78 | 79 | if (!string.IsNullOrWhiteSpace(user.State)) 80 | claims.Add(new Claim("address_state", user.State)); 81 | 82 | if (_userManager.SupportsUserEmail) 83 | { 84 | claims.AddRange(new[] 85 | { 86 | new Claim(JwtClaimTypes.Email, user.Email), 87 | new Claim(JwtClaimTypes.EmailVerified, user.EmailConfirmed ? "true" : "false", ClaimValueTypes.Boolean) 88 | }); 89 | } 90 | 91 | if (_userManager.SupportsUserPhoneNumber && !string.IsNullOrWhiteSpace(user.PhoneNumber)) 92 | { 93 | claims.AddRange(new[] 94 | { 95 | new Claim(JwtClaimTypes.PhoneNumber, user.PhoneNumber), 96 | new Claim(JwtClaimTypes.PhoneNumberVerified, user.PhoneNumberConfirmed ? "true" : "false", ClaimValueTypes.Boolean) 97 | }); 98 | } 99 | return claims; 100 | } 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /Module/JieDDDFramework.Module.Identity/Services/RedirectService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text.RegularExpressions; 3 | 4 | namespace JieDDDFramework.Module.Identity.Services 5 | { 6 | public class RedirectService : IRedirectService 7 | { 8 | public string ExtractRedirectUriFromReturnUrl(string url) 9 | { 10 | var result = ""; 11 | var decodedUrl = System.Net.WebUtility.HtmlDecode(url); 12 | var results = Regex.Split(decodedUrl, "redirect_uri="); 13 | if (results.Length < 2) 14 | return ""; 15 | 16 | result = results[1]; 17 | 18 | var splitKey = ""; 19 | if (result.Contains("signin-oidc")) 20 | splitKey = "signin-oidc"; 21 | else 22 | splitKey = "scope"; 23 | 24 | results = Regex.Split(result, splitKey); 25 | if (results.Length < 2) 26 | return ""; 27 | 28 | result = results[0]; 29 | 30 | return result.Replace("%3A", ":").Replace("%2F", "/").Replace("&", ""); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # JieDDDFramework 2 | 基于EntityFrameworkCore2.2实现的领域驱动框架,框架平台采用.NetCore2.2 3 | 4 | 适合中小型Web项目的开发,需要处理非常高并发的项目请采用[Ray](https://github.com/feijie999/Ray)框架 5 | 6 | ## 框架采用了以下技术: 7 | 8 | * AspNetCore2.2 9 | * Entity Framework Core2.2 10 | * 非侵入式的实体模型配置注入 11 | * 软删除支持 12 | * 实现`DomanDbContext`已更好的支持DDD 13 | * DDD领域驱动设计 14 | * (Entities/AggregateRoot)实体与领域根 15 | * Repositories 仓储模式,已实现Entity Framework。Example中使用了Mysql为数据库 16 | * Domain Event 基于MediatR实现 17 | * Unit Of Wrok工作单元模式,基于数据库实现的事务 18 | * 充血模式 19 | * 模块化开发与微服务架构 20 | * 依赖注入 21 | * 非侵入式的数据有效验证与统一的错误信息返回,包含错误码 22 | * 统一的异常拦截处理,业务领域层只需抛出异常,无需处理 23 | * 日志记录 24 | * EventBus 事件总线 (功能添加中) 25 | * 身份验证与授权管理,通过`IdentityServer4`实现 26 | 27 | ## Example 28 | 29 | **实现了两个模块:** 30 | 31 | * IdentityServer(Identity.API)认证服务中心 32 | * OrderServer (Order.API) 订单服务 33 | 34 | **环境** 35 | 36 | * dotnetcore 2.2 37 | * mysql 如使用其他关系型数据库需更改startup中如下代码已适配数据迁移功能 38 | ```csharp 39 | void OptionActions(DbContextOptionsBuilder option) 40 | { 41 | option.UseMySql(settings.ConnectionString, 42 | sqlOptions => { sqlOptions.MigrationsAssembly(assemblyName); }); 43 | } 44 | 45 | ``` 46 | 47 | **启动** 48 | 49 | 1. 配置appsettings.json中的数据库连接字符串 50 | 2. 启动Identity.API(http://localhost:5000/swagger/index.html) 51 | 3. 启动Order.API(http://localhost:8990/swagger/index.html) 52 | 4. 调用Order.API中的Login接口,参数{ 53 | "email": "demouser@xx.com", 54 | "password": "123456" 55 | }并得到accessToken 56 | 5. 在swagger中使用accessToken 57 | ![image](https://github.com/feijie999/JieDDDFramework/raw/master/docs/pic1.png) 58 | 6. 调用相关接口 59 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-cayman -------------------------------------------------------------------------------- /docs/pic1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/feijie999/JieDDDFramework/4d1df0089196c681b3ca78fe7d15442fb5976884/docs/pic1.png --------------------------------------------------------------------------------