[
  {
    "path": ".gitignore",
    "content": " Common IntelliJ Platform excludes\n\n# User specific\n\n.idea/\n\n**/.idea/**/workspace.xml\n**/.idea/**/tasks.xml\n**/.idea/shelf/*\n**/.idea/dictionaries\n\n# Sensitive or high-churn files\n**/.idea/**/dataSources/\n**/.idea/**/dataSources.ids\n**/.idea/**/dataSources.xml\n**/.idea/**/dataSources.local.xml\n**/.idea/**/sqlDataSources.xml\n**/.idea/**/dynamic.xml\n\n# Rider\n# Rider auto-generates .iml files, and contentModel.xml\n**/.idea/**/*.iml\n**/.idea/**/contentModel.xml\n**/.idea/**/modules.xml\n\n*.suo\n*.user\n.vs/\n[Bb]in/\n[Oo]bj/\n_UpgradeReport_Files/\n[Pp]ackages/\n\nThumbs.db\nDesktop.ini\n.DS_Store"
  },
  {
    "path": "Directory.build.props",
    "content": "<Project>\n    <PropertyGroup>\n        <Version>0.0.1</Version>\n\t\t<LangVersion>latest</LangVersion>\n    </PropertyGroup>\n</Project>\n"
  },
  {
    "path": "LICENSE",
    "content": "    Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License."
  },
  {
    "path": "README.md",
    "content": "## Experimental Product Domain Based On Hexagonal Architecture Principles\nThis project is a sample application built using .NET Core. The main goal of this project is implementing and better understanding DDD and hexagonal architecture principles.  \n# Also known as\n* Ports and Adapters\n* Clean Architecture\n* Onion Architecture\n# Hexagonal architecture\n![hexagonal](/hexagonal.png?raw=true \"hexagonal\")\n\n\n\nWith hexagonal architecture\n* Domain layer contains enterprise wide logic and types and does not depend anything except these \n* Application layer contains business logic and types\n* Infrastructure layer (including persistence, messaging, logging, presentation) contains all external concerns\n* Presentation and Infrastructure layers depend only on Application\n* Infrastructure dependencies can be replaced\nwith minimal effort. For instance, we can switch data store without touching business code. \n\n## Getting Started\nUse these instructions to get the project up and running.\n\n### Prerequisites\nYou will need the following tools:\n\n* [Visual Studio Code or 2019](https://www.visualstudio.com/downloads/) or [JetBrains Rider](https://www.jetbrains.com/rider/download)\n* [.NET Core SDK 3.0](https://www.microsoft.com/net/download/dotnet-core/3.0)\n\n### Setup\nFollow these steps to get your development environment set up:\n\n  1. Clone the repository\n  2. At the root directory, restore dependencies\n     ```\n     dotnet restore\n     ```\n  3. Build the solution\n     ```\n     dotnet build\n     ```\n  5. Run tests\n     ```\n     dotnet test\n\t ```\n## Technologies\n* .NET Core 3.0\n* ASP.NET Core 3.0\n## License\nThis project is licensed under the MIT License - see the [LICENSE.md](https://github.com/CanerPatir/aspnet-core-clean-arch/blob/master/LICENSE) file for details.\n## References\n* https://herbertograca.com/2017/11/16/explicit-architecture-01-ddd-hexagonal-onion-clean-cqrs-how-i-put-it-all-together/\n* https://blog.ploeh.dk/2013/12/03/layers-onions-ports-adapters-its-all-the-same/"
  },
  {
    "path": "aspnet-core-clean-arch.sln",
    "content": "﻿\nMicrosoft Visual Studio Solution File, Format Version 12.00\nProject(\"{2150E333-8FDC-42A3-9474-1A3956D46DE8}\") = \"src\", \"src\", \"{447CDAA9-FE29-40B2-AD2E-5B2AC8284965}\"\nEndProject\nProject(\"{2150E333-8FDC-42A3-9474-1A3956D46DE8}\") = \"test\", \"test\", \"{3E7CC539-9831-4E29-A871-B5A817584CCC}\"\nEndProject\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"Domain\", \"src\\Domain\\Domain.csproj\", \"{32905C1D-DCE3-439F-B9A9-CB5765934008}\"\nEndProject\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"Infrastructure\", \"src\\Infrastructure\\Infrastructure.csproj\", \"{8DD844E7-73F5-4EED-A37A-D431303D0FD7}\"\nEndProject\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"WebApi\", \"src\\WebApi\\WebApi.csproj\", \"{A6F7C54C-494B-44C7-86F0-D73FBC2DBF2B}\"\nEndProject\nProject(\"{2150E333-8FDC-42A3-9474-1A3956D46DE8}\") = \".solutionItems\", \".solutionItems\", \"{EE69A4C6-E7A9-4B6D-9B2F-CAFB23BDF6DF}\"\nProjectSection(SolutionItems) = preProject\n\tDirectory.build.props = Directory.build.props\n\tREADME.md = README.md\n\tLICENSE = LICENSE\n\thexagonal.png = hexagonal.png\nEndProjectSection\nEndProject\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"TestBase\", \"test\\TestBase\\TestBase.csproj\", \"{87282F82-F2FE-497E-BC35-2ACEEF151153}\"\nEndProject\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"Application\", \"src\\Application\\Application.csproj\", \"{B31F4D82-5454-4E30-9FD6-F520E144FEAC}\"\nEndProject\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"Domain.Specs\", \"test\\Domain.Specs\\Domain.Specs.csproj\", \"{CCEC4F14-D4A7-42A6-839D-A3676AED138F}\"\nEndProject\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"Application.Tests\", \"test\\Application.Tests\\Application.Tests.csproj\", \"{70A1D656-D4C6-40D8-9622-CB18313DACDA}\"\nEndProject\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"Infrastructure.Tests\", \"test\\Infrastructure.Tests\\Infrastructure.Tests.csproj\", \"{8C6E9314-A891-42F8-A516-180EE0132175}\"\nEndProject\nGlobal\n\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\n\t\tDebug|Any CPU = Debug|Any CPU\n\t\tRelease|Any CPU = Release|Any CPU\n\tEndGlobalSection\n\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\n\t\t{32905C1D-DCE3-439F-B9A9-CB5765934008}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\n\t\t{32905C1D-DCE3-439F-B9A9-CB5765934008}.Debug|Any CPU.Build.0 = Debug|Any CPU\n\t\t{32905C1D-DCE3-439F-B9A9-CB5765934008}.Release|Any CPU.ActiveCfg = Release|Any CPU\n\t\t{32905C1D-DCE3-439F-B9A9-CB5765934008}.Release|Any CPU.Build.0 = Release|Any CPU\n\t\t{8DD844E7-73F5-4EED-A37A-D431303D0FD7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\n\t\t{8DD844E7-73F5-4EED-A37A-D431303D0FD7}.Debug|Any CPU.Build.0 = Debug|Any CPU\n\t\t{8DD844E7-73F5-4EED-A37A-D431303D0FD7}.Release|Any CPU.ActiveCfg = Release|Any CPU\n\t\t{8DD844E7-73F5-4EED-A37A-D431303D0FD7}.Release|Any CPU.Build.0 = Release|Any CPU\n\t\t{A6F7C54C-494B-44C7-86F0-D73FBC2DBF2B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\n\t\t{A6F7C54C-494B-44C7-86F0-D73FBC2DBF2B}.Debug|Any CPU.Build.0 = Debug|Any CPU\n\t\t{A6F7C54C-494B-44C7-86F0-D73FBC2DBF2B}.Release|Any CPU.ActiveCfg = Release|Any CPU\n\t\t{A6F7C54C-494B-44C7-86F0-D73FBC2DBF2B}.Release|Any CPU.Build.0 = Release|Any CPU\n\t\t{87282F82-F2FE-497E-BC35-2ACEEF151153}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\n\t\t{87282F82-F2FE-497E-BC35-2ACEEF151153}.Debug|Any CPU.Build.0 = Debug|Any CPU\n\t\t{87282F82-F2FE-497E-BC35-2ACEEF151153}.Release|Any CPU.ActiveCfg = Release|Any CPU\n\t\t{87282F82-F2FE-497E-BC35-2ACEEF151153}.Release|Any CPU.Build.0 = Release|Any CPU\n\t\t{B31F4D82-5454-4E30-9FD6-F520E144FEAC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\n\t\t{B31F4D82-5454-4E30-9FD6-F520E144FEAC}.Debug|Any CPU.Build.0 = Debug|Any CPU\n\t\t{B31F4D82-5454-4E30-9FD6-F520E144FEAC}.Release|Any CPU.ActiveCfg = Release|Any CPU\n\t\t{B31F4D82-5454-4E30-9FD6-F520E144FEAC}.Release|Any CPU.Build.0 = Release|Any CPU\n\t\t{CCEC4F14-D4A7-42A6-839D-A3676AED138F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\n\t\t{CCEC4F14-D4A7-42A6-839D-A3676AED138F}.Debug|Any CPU.Build.0 = Debug|Any CPU\n\t\t{CCEC4F14-D4A7-42A6-839D-A3676AED138F}.Release|Any CPU.ActiveCfg = Release|Any CPU\n\t\t{CCEC4F14-D4A7-42A6-839D-A3676AED138F}.Release|Any CPU.Build.0 = Release|Any CPU\n\t\t{70A1D656-D4C6-40D8-9622-CB18313DACDA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\n\t\t{70A1D656-D4C6-40D8-9622-CB18313DACDA}.Debug|Any CPU.Build.0 = Debug|Any CPU\n\t\t{70A1D656-D4C6-40D8-9622-CB18313DACDA}.Release|Any CPU.ActiveCfg = Release|Any CPU\n\t\t{70A1D656-D4C6-40D8-9622-CB18313DACDA}.Release|Any CPU.Build.0 = Release|Any CPU\n\t\t{8C6E9314-A891-42F8-A516-180EE0132175}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\n\t\t{8C6E9314-A891-42F8-A516-180EE0132175}.Debug|Any CPU.Build.0 = Debug|Any CPU\n\t\t{8C6E9314-A891-42F8-A516-180EE0132175}.Release|Any CPU.ActiveCfg = Release|Any CPU\n\t\t{8C6E9314-A891-42F8-A516-180EE0132175}.Release|Any CPU.Build.0 = Release|Any CPU\n\tEndGlobalSection\n\tGlobalSection(NestedProjects) = preSolution\n\t\t{32905C1D-DCE3-439F-B9A9-CB5765934008} = {447CDAA9-FE29-40B2-AD2E-5B2AC8284965}\n\t\t{8DD844E7-73F5-4EED-A37A-D431303D0FD7} = {447CDAA9-FE29-40B2-AD2E-5B2AC8284965}\n\t\t{A6F7C54C-494B-44C7-86F0-D73FBC2DBF2B} = {447CDAA9-FE29-40B2-AD2E-5B2AC8284965}\n\t\t{87282F82-F2FE-497E-BC35-2ACEEF151153} = {3E7CC539-9831-4E29-A871-B5A817584CCC}\n\t\t{B31F4D82-5454-4E30-9FD6-F520E144FEAC} = {447CDAA9-FE29-40B2-AD2E-5B2AC8284965}\n\t\t{CCEC4F14-D4A7-42A6-839D-A3676AED138F} = {3E7CC539-9831-4E29-A871-B5A817584CCC}\n\t\t{70A1D656-D4C6-40D8-9622-CB18313DACDA} = {3E7CC539-9831-4E29-A871-B5A817584CCC}\n\t\t{8C6E9314-A891-42F8-A516-180EE0132175} = {3E7CC539-9831-4E29-A871-B5A817584CCC}\n\tEndGlobalSection\nEndGlobal\n"
  },
  {
    "path": "src/Application/Application.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n\n    <PropertyGroup>\n        <TargetFramework>netstandard2.1</TargetFramework>\n    </PropertyGroup>\n\n    <ItemGroup>\n      <ProjectReference Include=\"..\\Domain\\Domain.csproj\" />\n    </ItemGroup>\n\n    <ItemGroup>\n      <PackageReference Include=\"FluentValidation.AspNetCore\" Version=\"8.5.0\" />\n      <PackageReference Include=\"Microsoft.Extensions.DependencyInjection.Abstractions\" Version=\"3.0.0\" />\n    </ItemGroup>\n\n</Project>\n"
  },
  {
    "path": "src/Application/ICommandHandler.cs",
    "content": "using System.Threading;\nusing System.Threading.Tasks;\n\nnamespace Application\n{\n    public interface ICommandHandler<in TMessage>\n    {\n        Task Handle(TMessage message, CancellationToken cancellationToken);\n    }\n}"
  },
  {
    "path": "src/Application/IEventHandler.cs",
    "content": "using System.Threading;\nusing System.Threading.Tasks;\n\nnamespace Application\n{\n    public interface IEventHandler <in TEvent>\n    {\n        Task Handle(TEvent @event, CancellationToken cancellationToken);\n    }\n}"
  },
  {
    "path": "src/Application/IQueryHandler.cs",
    "content": "using System.Threading;\nusing System.Threading.Tasks;\n\nnamespace Application\n{\n    public interface IQueryHandler<in TMessage, TResult>\n    {\n        Task<TResult> Handle(TMessage message, CancellationToken cancellationToken);\n    }\n}"
  },
  {
    "path": "src/Application/UseCases/AddContentToProduct/AddContentToProductCommand.cs",
    "content": "using System;\n\nnamespace Application.UseCases.AddContentToProduct\n{\n    public class AddContentToProductCommand\n    {\n        public AddContentToProductCommand(Guid productId, string title, string description,\n            int attributeId, int attributeValueId)\n        {\n            ProductId = productId;\n            Title = title;\n            Description = description;\n            AttributeId = attributeId;\n            AttributeValueId = attributeValueId;\n        }\n\n        public Guid ProductId { get; }\n        public string Title { get; }\n        public string Description { get; }\n        public int AttributeId { get; }\n        public int AttributeValueId { get; }\n    }\n}"
  },
  {
    "path": "src/Application/UseCases/AddContentToProduct/AddContentToProductCommandHandler.cs",
    "content": "using System.Threading;\nusing System.Threading.Tasks;\nusing Domain.ProductContext;\n\nnamespace Application.UseCases.AddContentToProduct\n{\n    public class AddContentToProductCommandHandler : ICommandHandler<AddContentToProductCommand>\n    {\n        private readonly IProductRepository _productRepository;\n\n        public AddContentToProductCommandHandler(IProductRepository productRepository)\n        {\n            _productRepository = productRepository;\n        }\n\n        public async Task Handle(AddContentToProductCommand command, CancellationToken cancellationToken)\n        {\n            var aggregate = await _productRepository.Load(command.ProductId, cancellationToken);\n\n            aggregate.AddContent(command.Title, command.Description,\n                new AttributeRef(command.AttributeId, command.AttributeValueId));\n\n            await _productRepository.Save(aggregate, cancellationToken);\n        }\n    }\n}"
  },
  {
    "path": "src/Application/UseCases/CreateProduct/CreateProductCommand.cs",
    "content": "namespace Application.UseCases.CreateProduct\n{\n    public class CreateProductCommand\n    {\n        public CreateProductCommand(int categoryId, int brandId, string productCode)\n        {\n            CategoryId = categoryId;\n            BrandId = brandId;\n            ProductCode = productCode;\n        }\n\n        public int CategoryId { get; }\n        public int BrandId { get; }\n        public string ProductCode { get; }\n        \n    }\n}"
  },
  {
    "path": "src/Application/UseCases/CreateProduct/CreateProductCommandHandler.cs",
    "content": "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Domain.ProductContext;\n\nnamespace Application.UseCases.CreateProduct\n{\n    public class CreateProductCommandHandler : ICommandHandler<CreateProductCommand>\n    {\n        private readonly IProductRepository _productRepository;\n\n        public CreateProductCommandHandler(IProductRepository productRepository)\n        {\n            _productRepository = productRepository;\n        }\n\n        public async Task Handle(CreateProductCommand command, CancellationToken cancellationToken)\n        {\n            var newProduct = Product.Create(Guid.NewGuid(), command.CategoryId, command.BrandId, command.ProductCode);\n            \n            await _productRepository.Save(newProduct, cancellationToken);\n        }\n    }\n}"
  },
  {
    "path": "src/Domain/Abstraction/AggregateRoot.cs",
    "content": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\n\nnamespace Domain\n{\n    public interface IAggregateRoot\n    {\n        int Version { get; }\n        bool HasChanges();\n        IEnumerable<object> GetUncommittedChanges();\n        void MarkChangesAsCommitted();\n        void LoadsFromHistory(IEnumerable<object> history);\n    }\n\n    public abstract class AggregateRoot<TKey> : IAggregateRoot\n    {\n        private readonly List<object> _changes = new List<object>();\n        private readonly InstanceEventRouter _router;\n\n        public AggregateRoot()\n        {\n            _router = new InstanceEventRouter();\n        }\n\n        public virtual TKey Id { get; protected set; }\n\n        public virtual int Version { get; protected set; }\n\n        public bool HasChanges() => _changes.Any();\n\n        public IEnumerable<object> GetUncommittedChanges()\n        {\n            return _changes;\n        }\n\n        public void MarkChangesAsCommitted()\n        {\n            _changes.Clear();\n        }\n\n        public void LoadsFromHistory(IEnumerable<object> history)\n        {\n            foreach (var e in history) ApplyChange(e, false);\n        }\n\n        protected void Register<TEvent>(Action<TEvent> handler)\n        {\n            if (handler == null) throw new ArgumentNullException(nameof(handler));\n            _router.ConfigureRoute(handler);\n        }\n\n        protected void ApplyChange(object @event)\n        {\n            ApplyChange(@event, true);\n        }\n\n        protected void ApplyChange(object @event, bool isNew)\n        {\n            if (@event == null) throw new ArgumentNullException(nameof(@event));\n\n            _router.Route(@event);\n            if (isNew)\n            {\n                _changes.Add(@event);\n                Version++;\n            }\n        }\n\n        #region overrides\n\n        /// <inheritdoc />\n        /// <summary>\n        ///     Checks if this entity is transient (it has not an Id).\n        /// </summary>\n        /// <returns>True, if this entity is transient</returns>\n        public virtual bool IsTransient()\n        {\n            if (EqualityComparer<TKey>.Default.Equals(Id, default))\n            {\n                return true;\n            }\n\n            //Workaround for EF Core since it sets int/long to min value when attaching to dbcontext\n            if (typeof(TKey) == typeof(int))\n            {\n                return Convert.ToInt32(Id) <= 0;\n            }\n\n            if (typeof(TKey) == typeof(long))\n            {\n                return Convert.ToInt64(Id) <= 0;\n            }\n\n            return false;\n        }\n\n        public override bool Equals(object obj)\n        {\n            if (!(obj is AggregateRoot<TKey>))\n            {\n                return false;\n            }\n\n            //Same instances must be considered as equal\n            if (ReferenceEquals(this, obj))\n            {\n                return true;\n            }\n\n            //Transient objects are not considered as equal\n            var other = (AggregateRoot<TKey>) obj;\n            if (IsTransient() && other.IsTransient())\n            {\n                return false;\n            }\n\n            //Must have a IS-A relation of types or must be same type\n            var typeOfThis = GetType();\n            var typeOfOther = other.GetType();\n            if (!typeOfThis.GetTypeInfo().IsAssignableFrom(typeOfOther) &&\n                !typeOfOther.GetTypeInfo().IsAssignableFrom(typeOfThis))\n            {\n                return false;\n            }\n\n            return Id.Equals(other.Id);\n        }\n\n        public override int GetHashCode() => Id.GetHashCode();\n\n        public static bool operator ==(AggregateRoot<TKey> left, AggregateRoot<TKey> right)\n        {\n            if (Equals(left, null))\n            {\n                return Equals(right, null);\n            }\n\n            return left.Equals(right);\n        }\n\n        public static bool operator !=(AggregateRoot<TKey> left, AggregateRoot<TKey> right) =>\n            !(left == right);\n\n        #endregion\n\n        #region rule helpers\n\n        protected void Should(Func<bool> predicate)\n        {\n            Should(predicate());\n        }\n\n        protected void Should(Func<bool> predicate, string otherwiseMessage)\n        {\n            Should(predicate(), otherwiseMessage);\n        }\n\n        protected void Should(bool clause)\n        {\n            if (clause) return;\n            throw new BusinessException();\n        }\n\n        protected void Should(bool clause, string otherwiseMessage)\n        {\n            if (clause) return;\n            throw new BusinessException(otherwiseMessage);\n        }\n\n        #endregion\n    }\n}"
  },
  {
    "path": "src/Domain/Abstraction/BaseDomainEvent.cs",
    "content": "namespace Domain.Abstraction\n{\n    public class BaseDomainEvent\n    {\n        public int Version { get; set; }\n    }\n}"
  },
  {
    "path": "src/Domain/Abstraction/Entity.cs",
    "content": "﻿using System;\n\nnamespace Domain\n{\n    public abstract class Entity \n    {\n        private readonly InstanceEventRouter _router;\n\n        protected Entity() => _router = new InstanceEventRouter();\n\n        protected void Register<TEvent>(Action<TEvent> handler)\n        {\n            if (handler == null)\n            {\n                throw new ArgumentNullException(nameof(handler));\n            }\n\n            _router.ConfigureRoute(handler);\n        }\n\n        public virtual void Route(object @event)\n        {\n            if (@event == null)\n            {\n                throw new ArgumentNullException(nameof(@event));\n            }\n\n            _router.Route(@event);\n        }\n    }\n}"
  },
  {
    "path": "src/Domain/Abstraction/IRepository.cs",
    "content": "using System.Threading;\nusing System.Threading.Tasks;\n\nnamespace Domain.Abstraction\n{\n    /// <summary>\n    /// Provides an abstraction for object sotrage and\n    /// </summary>\n    /// <typeparam name=\"T\">Type of aggregate root</typeparam>\n    /// <typeparam name=\"TKey\">Type of aggregate root's key</typeparam>\n    public interface IRepository<T, TKey> where T : AggregateRoot<TKey>\n    {\n        Task Save(T aggregate, CancellationToken cancellationToken);\n        Task<T> Load(TKey id, CancellationToken cancellationToken);\n    }\n}"
  },
  {
    "path": "src/Domain/Abstraction/InstanceEventRouter.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\n\nnamespace Domain\n{\n    /// <summary>\n    ///     Routes an event to a configured state handler.\n    /// </summary>\n    internal class InstanceEventRouter\n    {\n        private readonly Dictionary<Type, Action<object>> _handlers;\n\n        /// <summary>\n        ///     Initializes a new instance of the <see cref=\"InstanceEventRouter\" /> class.\n        /// </summary>\n        public InstanceEventRouter() => _handlers = new Dictionary<Type, Action<object>>();\n\n        /// <summary>\n        ///     Adds a route for the specified event type to the specified state handler.\n        /// </summary>\n        /// <param name=\"event\">The event type the route is for.</param>\n        /// <param name=\"handler\">The state handler that should be invoked when an event of the specified type is routed.</param>\n        /// <exception cref=\"ArgumentNullException\">\n        ///     Thrown when <paramref name=\"event\" /> or <paramref name=\"handler\" /> is\n        ///     <c>null</c>.\n        /// </exception>\n        public void ConfigureRoute(Type @event, Action<object> handler)\n        {\n            if (@event == null)\n            {\n                throw new ArgumentNullException(nameof(@event));\n            }\n\n            if (handler == null)\n            {\n                throw new ArgumentNullException(nameof(handler));\n            }\n\n            _handlers.Add(@event, handler);\n        }\n\n        /// <summary>\n        ///     Adds a route for the specified event type to the specified state handler.\n        /// </summary>\n        /// <typeparam name=\"TEvent\">The event type the route is for.</typeparam>\n        /// <param name=\"handler\">The state handler that should be invoked when an event of the specified type is routed.</param>\n        /// <exception cref=\"T:System.ArgumentNullException\">Thrown when <paramref name=\"handler\" /> is <c>null</c>.</exception>\n        public void ConfigureRoute<TEvent>(Action<TEvent> handler)\n        {\n            if (handler == null)\n            {\n                throw new ArgumentNullException(nameof(handler));\n            }\n\n            _handlers.Add(typeof(TEvent), @event => handler((TEvent) @event));\n        }\n\n        /// <summary>\n        ///     Routes the specified <paramref name=\"event\" /> to a configured state handler, if any.\n        /// </summary>\n        /// <param name=\"event\">The event to route.</param>\n        /// <exception cref=\"T:System.ArgumentNullException\">Thrown when the <paramref name=\"event\" /> is null.</exception>\n        public void Route(object @event)\n        {\n            if (@event == null)\n            {\n                throw new ArgumentNullException(nameof(@event));\n            }\n\n            if (_handlers.TryGetValue(@event.GetType(), out var handler))\n            {\n                handler(@event);\n            }\n        }\n    }\n\n}"
  },
  {
    "path": "src/Domain/Abstraction/ValueObject.cs",
    "content": "using System;\nusing System.Linq;\n\nnamespace Domain\n{\n      //Inspired from https://blogs.msdn.microsoft.com/cesardelatorre/2011/06/06/implementing-a-value-object-base-class-supertype-patternddd-patterns-related/\n    /// <summary>\n    ///     Base class for value objects.\n    /// </summary>\n    /// <typeparam name=\"TValueObject\">The type of the value object.</typeparam>\n    public abstract class ValueObject<TValueObject> : IEquatable<TValueObject>\n        where TValueObject : ValueObject<TValueObject>\n    {\n        public bool Equals(TValueObject other)\n        {\n            if ((object) other == null)\n            {\n                return false;\n            }\n\n            var publicProperties = GetType().GetProperties();\n            if (!publicProperties.Any())\n            {\n                return true;\n            }\n\n            return publicProperties.All(property =>\n                Equals(property.GetValue(this, null), property.GetValue(other, null)));\n        }\n\n        public override bool Equals(object obj)\n        {\n            if (obj == null)\n            {\n                return false;\n            }\n\n            var item = obj as ValueObject<TValueObject>;\n            return (object) item != null && Equals((TValueObject) item);\n        }\n\n        public override int GetHashCode()\n        {\n            const int index = 1;\n            const int initialHasCode = 31;\n\n            var publicProperties = GetType().GetProperties();\n\n            if (!publicProperties.Any())\n            {\n                return initialHasCode;\n            }\n\n            var hashCode = initialHasCode;\n            var changeMultiplier = false;\n\n            foreach (var property in publicProperties)\n            {\n                var value = property.GetValue(this, null);\n\n                if (value == null)\n                {\n                    //support {\"a\",null,null,\"a\"} != {null,\"a\",\"a\",null}\n                    hashCode = hashCode ^ (index * 13);\n                    continue;\n                }\n\n                hashCode = hashCode * (changeMultiplier ? 59 : 114) + value.GetHashCode();\n                changeMultiplier = !changeMultiplier;\n            }\n\n            return hashCode;\n        }\n\n        public static bool operator ==(ValueObject<TValueObject> x, ValueObject<TValueObject> y)\n        {\n            if (ReferenceEquals(x, y))\n            {\n                return true;\n            }\n\n            if ((object) x == null || (object) y == null)\n            {\n                return false;\n            }\n\n            return x.Equals(y);\n        }\n\n        public static bool operator !=(ValueObject<TValueObject> x, ValueObject<TValueObject> y) => !(x == y);\n    }\n}"
  },
  {
    "path": "src/Domain/BusinessException.cs",
    "content": "using System;\n\nnamespace Domain\n{\n    public class BusinessException : Exception\n    {\n        public BusinessException()\n        {\n        }\n\n        public BusinessException(string message) : base(message)\n        {\n        }\n        \n        public BusinessException(string message, Exception innerException) : base(message, innerException)\n        {\n        }\n    }\n}"
  },
  {
    "path": "src/Domain/Domain.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n\n    <PropertyGroup>\n        <TargetFramework>netstandard2.1</TargetFramework>\n    </PropertyGroup>\n\n</Project>\n"
  },
  {
    "path": "src/Domain/ProductContext/AttributeRef.cs",
    "content": "namespace Domain.ProductContext\n{\n    public class AttributeRef : ValueObject<AttributeRef>\n    {\n        public AttributeRef(int attributeId, int attributeValueId)\n        {\n            AttributeId = attributeId;\n            AttributeValueId = attributeValueId;\n        }\n\n        /// <summary>\n        /// Represents attribute for example: color, size, material etc.\n        /// </summary>\n        public int AttributeId { get; }\n\n        /// <summary>\n        /// Represents value of attribute for example: Red, Small, Cotton etc. \n        /// </summary>\n        public int AttributeValueId { get; }\n\n    }\n}"
  },
  {
    "path": "src/Domain/ProductContext/BrandRef.cs",
    "content": "namespace Domain.ProductContext\n{\n    public class BrandRef : ValueObject<BrandRef>\n    {\n        public BrandRef(int id, string name)\n        {\n            Id = id;\n            Name = name;\n        }\n\n        public int Id { get; }\n\n        public string Name { get; }\n    }\n}"
  },
  {
    "path": "src/Domain/ProductContext/CategoryRef.cs",
    "content": "namespace Domain.ProductContext\n{\n    public class CategoryRef : ValueObject<CategoryRef>\n    {\n        public CategoryRef(int id, string name)\n        {\n            Id = id;\n            Name = name;\n        }\n\n        public int Id { get; }\n\n        public string Name { get; }\n    }\n}"
  },
  {
    "path": "src/Domain/ProductContext/Content.cs",
    "content": "using System.Collections.Generic;\nusing System.Linq;\nusing Domain.ProductContext.Events;\n\nnamespace Domain.ProductContext\n{\n    /// <summary>\n    /// Represents group of product variant and can be projection of product detail page.  \n    /// </summary>\n    public class Content : Entity\n    {\n        private ICollection<Variant> _variants = new HashSet<Variant>();\n\n        internal Content(string title, string description, AttributeRef slicerAttribute)\n        {\n            Title = title;\n            Description = description;\n            SlicerAttribute = slicerAttribute;\n            \n            Register<VariantAddedToProduct>(Apply);\n        }\n\n        private void Apply(VariantAddedToProduct @event)\n        {\n            _variants.Add(new Variant(@event.Barcode, @event.VarianterAttribute));\n        }\n\n        public IReadOnlyCollection<Variant> Variants => _variants.ToList();\n        \n        public string Title { get; private set; }\n\n        public string Description { get; private set; }\n\n        public AttributeRef SlicerAttribute { get; private set; }\n\n        public bool HasSameTypeSlicerAttribute(AttributeRef attribute)\n        {\n            return SlicerAttribute.AttributeId == attribute.AttributeId;\n        }\n\n    }\n}"
  },
  {
    "path": "src/Domain/ProductContext/Events/AttributeAddedToProduct.cs",
    "content": "using System;\n\nnamespace Domain.ProductContext.Events\n{\n    public class AttributeAddedToProduct : BaseProductEvent\n    {\n        public AttributeAddedToProduct(Guid productId, AttributeRef attribute)\n        {\n            ProductId = productId;\n            Attribute = attribute;\n        }\n\n        public override Guid ProductId { get; }\n        public AttributeRef Attribute { get; }\n    }\n}"
  },
  {
    "path": "src/Domain/ProductContext/Events/BaseProductEvent.cs",
    "content": "using System;\nusing Domain.Abstraction;\n\nnamespace Domain.ProductContext.Events\n{\n    public abstract class BaseProductEvent : BaseDomainEvent\n    {\n        public abstract Guid ProductId { get; }\n    }\n}"
  },
  {
    "path": "src/Domain/ProductContext/Events/ContentAddedToProduct.cs",
    "content": "using System;\n\nnamespace Domain.ProductContext.Events\n{\n    public class ContentAddedToProduct : BaseProductEvent\n    {\n        public ContentAddedToProduct(Guid productId, string title, string description, AttributeRef slicerAttribute)\n        {\n            ProductId = productId;\n            Title = title;\n            Description = description;\n            SlicerAttribute = slicerAttribute;\n        }\n\n        public override Guid ProductId { get; }\n        public string Title { get; }\n        public string Description { get; }\n        public AttributeRef SlicerAttribute { get; }\n    }\n}"
  },
  {
    "path": "src/Domain/ProductContext/Events/ImageAddedToProduct.cs",
    "content": "using System;\n\nnamespace Domain.ProductContext.Events\n{\n    public class ImageAddedToProduct :BaseProductEvent\n    {\n        public ImageAddedToProduct(Guid productId, AttributeRef varianterAttr, ImageRef image)\n        {\n            ProductId = productId;\n            VarianterAttr = varianterAttr;\n            Image = image;\n        }\n\n        public override Guid ProductId { get; }\n        public AttributeRef VarianterAttr { get; }\n        public ImageRef Image { get; }\n    }\n}"
  },
  {
    "path": "src/Domain/ProductContext/Events/ProductApproved.cs",
    "content": "using System;\n\nnamespace Domain.ProductContext.Events\n{\n    public class ProductApproved : BaseProductEvent\n    {\n        public ProductApproved(Guid productId)\n        {\n            ProductId = productId;\n        }\n\n        public override Guid ProductId { get; }\n    }\n}"
  },
  {
    "path": "src/Domain/ProductContext/Events/ProductCreated.cs",
    "content": "using System;\n\nnamespace Domain.ProductContext.Events\n{\n    public class ProductCreated : BaseProductEvent\n    {\n        public ProductCreated(Guid productId, string productCode, int brandId, int categoryId)\n        {\n            ProductId = productId;\n            BrandId = brandId;\n            ProductCode = productCode;\n            CategoryId = categoryId;\n        }\n\n        public override Guid ProductId { get; }\n        public int BrandId { get; }\n        public string ProductCode { get; }\n        public int CategoryId { get; }\n    }\n}"
  },
  {
    "path": "src/Domain/ProductContext/Events/VariantAddedToProduct.cs",
    "content": "using System;\n\nnamespace Domain.ProductContext.Events\n{\n    public class VariantAddedToProduct: BaseProductEvent\n    {\n        public VariantAddedToProduct(Guid productId, string barcode, AttributeRef slicerAttribute, AttributeRef varianterAttribute)\n        {\n            ProductId = productId;\n            Barcode = barcode;\n            SlicerAttribute = slicerAttribute;\n            VarianterAttribute = varianterAttribute;\n        }\n\n        public override Guid ProductId { get; }\n        public string Barcode { get; }\n        public AttributeRef SlicerAttribute { get; }\n        public AttributeRef VarianterAttribute { get; }\n    }\n}"
  },
  {
    "path": "src/Domain/ProductContext/IProductRepository.cs",
    "content": "using System;\nusing Domain.Abstraction;\n\nnamespace Domain.ProductContext\n{\n    public interface IProductRepository : IRepository<Product, Guid>\n    {\n    }\n}"
  },
  {
    "path": "src/Domain/ProductContext/ImageRef.cs",
    "content": "namespace Domain.ProductContext\n{\n    public class ImageRef : ValueObject<ImageRef>\n    {\n        public ImageRef(string relativeUrl, string relativeThumbUrl)\n        {\n            RelativeUrl = relativeUrl;\n            RelativeThumbUrl = relativeThumbUrl;\n        }\n\n        public string RelativeUrl { get; }\n        public string RelativeThumbUrl { get; }\n    }\n}"
  },
  {
    "path": "src/Domain/ProductContext/Product.cs",
    "content": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Domain.ProductContext.Events;\n\nnamespace Domain.ProductContext\n{\n    public class Product : AggregateRoot<Guid>\n    {\n        private readonly ICollection<AttributeRef> _attributes = new HashSet<AttributeRef>();\n\n        private readonly ICollection<Content> _contents = new HashSet<Content>();\n\n        public Product()\n        {\n            Register<ProductCreated>(Apply);\n            Register<ContentAddedToProduct>(Apply);\n            Register<AttributeAddedToProduct>(Apply);\n            Register<VariantAddedToProduct>(Apply);\n            Register<ProductApproved>(Apply);\n            Register<ImageAddedToProduct>(Apply);\n        }\n\n        public static Product Create(Guid productId,\n            int categoryId,\n            int brandId,\n            string productCode)\n        {\n            var product =  new Product();\n            product.ApplyChange(\n                new ProductCreated(productId,\n                    productCode,\n                    brandId, categoryId));\n\n            return product;\n        }\n\n        public BrandRef Brand { get; private set; }\n\n        public CategoryRef Category { get; private set; }\n\n        public string Code { get; private set; }\n\n        public IReadOnlyCollection<Content> Contents => _contents.ToList();\n\n        public IReadOnlyCollection<AttributeRef> Attributes => _attributes.ToList();\n        \n        protected IReadOnlyCollection<Variant> Variants => _contents.SelectMany(c => c.Variants).ToList();\n        \n        protected IReadOnlyCollection<ImageRef> Images => Variants.SelectMany(c => c.Images).ToList();\n\n        public bool IsApproved { get; private set; }\n        \n        private void Apply(ProductApproved @event) => IsApproved = true;\n\n        private void Apply(ContentAddedToProduct @event) => _contents.Add(new Content(@event.Title, @event.Description, @event.SlicerAttribute));\n\n        private void Apply(AttributeAddedToProduct @event) => _attributes.Add(@event.Attribute);\n\n        private void Apply(VariantAddedToProduct @event) => _contents.First(c => c.SlicerAttribute == @event.SlicerAttribute).Route(@event);\n\n        private void Apply(ProductCreated @event)\n        {\n            Id = @event.ProductId;\n            Brand = new BrandRef(@event.BrandId, \"\");\n            Category = new CategoryRef(@event.CategoryId, \"\");\n            Code = @event.ProductCode;\n        }\n        \n        private void Apply(ImageAddedToProduct @event)\n        {\n            var variant = _contents.SelectMany(c => c.Variants)\n                .SingleOrDefault(v => v.VarianterAttribute == @event.VarianterAttr);\n            \n            // ReSharper disable once PossibleNullReferenceException\n            variant.Route(@event);\n        }\n        \n        public void AddContent(string title, string description, AttributeRef slicerAttribute)\n        {\n            if (_contents.Any())\n            {\n                Should(() => _contents.Any(c => c.HasSameTypeSlicerAttribute(slicerAttribute)),\n                    \"Given attribute type should belong to any content of product as slicer\");\n            }\n            \n            Should(() => _contents.All(c => c.SlicerAttribute != slicerAttribute),\n                \"Same content already exists with given attribute\");\n\n            ApplyChange(new ContentAddedToProduct(Id, title, description, slicerAttribute));\n        }\n        \n        public void AddVariant(string barcode, AttributeRef slicerAttribute, AttributeRef varianterAttribute)\n        {\n            var content = _contents.SingleOrDefault(c => c.SlicerAttribute == slicerAttribute);\n            Should(() => content != null, \"No content found with given slicer attribute.\");\n            \n            // ReSharper disable once PossibleNullReferenceException\n            var variantsOfContent = content.Variants;\n\n            if (variantsOfContent.Any())\n            {\n                Should(() =>  variantsOfContent.All(c => c.HasSameTypeVarianterAttribute(varianterAttribute)),\n                    \"Given attribute type should belong to any variant of product as varianter\");\n            }\n            \n            Should(() => variantsOfContent.All(v => v.VarianterAttribute != varianterAttribute) ,\n                \"Same variant already exists with given attribute\");\n            \n            ApplyChange(new VariantAddedToProduct(Id, barcode, slicerAttribute, varianterAttribute));\n        }\n\n        public void AddAttributeToContent(AttributeRef attribute)\n        {\n            Should(() => _attributes.Any(a => a != attribute),\n                \"Given attribute had already been added to the product\");\n\n            ApplyChange(new AttributeAddedToProduct(Id, attribute));\n        }\n        \n        public void Approve()\n        {\n            Should(() => _contents.Any(), \"Product must have at least one content\");\n            Should(() => Variants.Any(), \"Product must have at least one variant\");\n            Should(() => Variants.SelectMany(v => v.Images).Any(), \"Product must have at least one image\");\n            \n            ApplyChange(new ProductApproved(Id));\n        } \n        \n        public void AssignImage(ImageRef image, AttributeRef varianterAttr)\n        {\n            Should(() => Variants.Any(v => v.HasSameTypeVarianterAttribute(varianterAttr)),\n                $\"Product does not have any attribute with given attributeId: {varianterAttr.AttributeId}\");\n            \n            ApplyChange(new ImageAddedToProduct(Id, varianterAttr, image));\n        }\n    }\n\n}"
  },
  {
    "path": "src/Domain/ProductContext/Variant.cs",
    "content": "using System.Collections.Generic;\nusing System.Linq;\nusing Domain.ProductContext.Events;\n\nnamespace Domain.ProductContext\n{\n    public class Variant : Entity\n    {\n        private readonly ICollection<ImageRef> _images = new HashSet<ImageRef>();\n\n        internal Variant(string barcode, AttributeRef varianterAttribute)\n        {\n            Barcode = barcode;\n            VarianterAttribute = varianterAttribute;\n            \n            Register<ImageAddedToProduct>(Apply);\n        }\n\n        private void Apply(ImageAddedToProduct @event)\n        {\n            _images.Add(@event.Image);\n        }\n\n        public IReadOnlyCollection<ImageRef> Images => _images.ToList();\n        \n        public string Barcode { get; }\n\n        public AttributeRef VarianterAttribute { get; }\n        \n        public bool HasSameTypeVarianterAttribute(AttributeRef attribute)\n        {\n            return VarianterAttribute.AttributeId == attribute.AttributeId;\n        }\n    }\n}"
  },
  {
    "path": "src/Infrastructure/Infrastructure.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n\n    <PropertyGroup>\n        <TargetFramework>netstandard2.1</TargetFramework>\n    </PropertyGroup>\n\n    <ItemGroup>\n\n         \n        <PackageReference Include=\"Microsoft.AspNetCore\" Version=\"2.2.0\" /> \n        \n        <PackageReference Include=\"Microsoft.Extensions.DependencyInjection\" Version=\"3.0.0\" />\n        <PackageReference Include=\"Microsoft.Extensions.Logging\" Version=\"3.0.0\" />\n        <PackageReference Include=\"MongoDB.Driver\" Version=\"2.9.2\" />\n        <PackageReference Include=\"System.Threading.Tasks.Dataflow\" Version=\"4.10.0\" />\n        <PackageReference Include=\"Swashbuckle.AspNetCore\" Version=\"4.0.1\" />\n\n\n        <PackageReference Include=\"Serilog.AspNetCore\" Version=\"3.0.0\" />\n        <PackageReference Include=\"Serilog.Sinks.ColoredConsole\" Version=\"3.0.1\" />\n        <PackageReference Include=\"Serilog.Settings.Configuration\" Version=\"3.1.0\" />\n        <PackageReference Include=\"Serilog.Sinks.Graylog\" Version=\"2.0.12\" />\n    </ItemGroup>\n\n    <ItemGroup>\n      <ProjectReference Include=\"..\\Application\\Application.csproj\" />\n    </ItemGroup>\n\n</Project>\n"
  },
  {
    "path": "src/Infrastructure/Logging/WebHostExtensions.cs",
    "content": "using System.Reflection;\nusing Microsoft.AspNetCore.Hosting;\nusing Microsoft.Extensions.Configuration;\nusing Microsoft.Extensions.Logging;\nusing Serilog;\nusing Serilog.Events;\nusing Serilog.Sinks.Graylog;\nusing Serilog.Sinks.Graylog.Core.Helpers;\nusing Serilog.Sinks.Graylog.Core.Transport;\n\nnamespace Infrastructure.Logging\n{\n    public static class WebHostExtensions\n    {\n        public static IWebHostBuilder ConfigureLoggingPlumbing(this IWebHostBuilder webHostBuilder)\n        {\n            return webHostBuilder.UseSerilog((context, loggerConfiguration) =>\n            {\n                var logLevel = context.Configuration.GetValue<LogEventLevel>(\"Serilog:MinimumLevel:Default\");\n                loggerConfiguration\n                    .MinimumLevel.Verbose()\n                    .Enrich.FromLogContext()\n                    .Enrich.WithProperty(\"version\",\n                        Assembly.GetExecutingAssembly().GetCustomAttribute<AssemblyFileVersionAttribute>().Version)\n                    .Enrich.WithProperty(\"env\", context.HostingEnvironment.EnvironmentName)\n                    .ReadFrom.Configuration(context.Configuration)\n                    .WriteTo.Graylog(\n                        new GraylogSinkOptions\n                        {\n                            HostnameOrAddress = context.Configuration[\"Serilog:GraylogIp\"],\n                            Port = int.Parse(context.Configuration[\"Serilog:GraylogPort\"]),\n                            TransportType = TransportType.Udp,\n                            MinimumLogEventLevel = logLevel,\n                            Facility = context.Configuration[\"Serilog:FacilityName\"],\n                            MessageGeneratorType = MessageIdGeneratortype.Timestamp\n                        });\n\n                if (context.Configuration.GetValue<bool>(\"Serilog:Console\"))\n                {\n                    loggerConfiguration.WriteTo.ColoredConsole(logLevel,\n                        \"[{Timestamp:yyyy-MM-dd HH:mm:ss} {Level:u3}] {SourceContext}: {Message:lj}{NewLine}{Exception}\");\n                }\n            });\n        }\n    }\n}"
  },
  {
    "path": "src/Infrastructure/Messaging/Mediator/IMediator.cs",
    "content": "using System.Threading;\nusing System.Threading.Tasks;\n\nnamespace Infrastructure.Messaging.Mediator\n{\n    public interface IMediator\n    {\n        Task SendAsync<TMessage>(TMessage message, CancellationToken cancellationToken = default);\n        Task PublishAsync<TEvent>(TEvent message, CancellationToken cancellationToken = default);\n        Task<TResult> SendAsync<TMessage, TResult>(TMessage @event, CancellationToken cancellationToken = default);\n    }\n}"
  },
  {
    "path": "src/Infrastructure/Messaging/Mediator/Mediator.cs",
    "content": "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Application;\nusing Microsoft.Extensions.DependencyInjection;\n\nnamespace Infrastructure.Messaging.Mediator\n{\n    public class Mediator : IMediator\n    {\n        private readonly IServiceProvider _serviceProvider;\n\n        public Mediator(IServiceProvider serviceProvider)\n        {\n            _serviceProvider = serviceProvider;\n        }\n\n        public Task SendAsync<TMessage>(TMessage message, CancellationToken cancellationToken)\n        {\n            var handler = _serviceProvider.GetRequiredService<ICommandHandler<TMessage>>();\n            if (handler == null) throw new NullReferenceException($\"handler of {nameof(TMessage)}\");\n\n            return handler.Handle(message, cancellationToken);\n        }\n\n        public Task PublishAsync<TEvent>(TEvent @event, CancellationToken cancellationToken = default)\n        {\n            var handler = _serviceProvider.GetRequiredService<IEventHandler<TEvent>>();\n            if (handler == null) throw new NullReferenceException($\"handler of {nameof(TEvent)}\");\n\n            return handler.Handle(@event, cancellationToken);        }\n\n        public Task<TResult> SendAsync<TMessage, TResult>(TMessage message, CancellationToken cancellationToken)\n        {\n            var handler = _serviceProvider.GetRequiredService<IQueryHandler<TMessage, TResult>>();\n            if (handler == null)\n                throw new NullReferenceException($\"handler of {nameof(TMessage)} which returning {nameof(TResult)}\");\n\n            return handler.Handle(message, cancellationToken);\n        }\n    }\n}"
  },
  {
    "path": "src/Infrastructure/Messaging/Mediator/ServiceCollectionExtensions.cs",
    "content": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing Application;\nusing Infrastructure.Messaging.Mediator;\nusing Microsoft.Extensions.DependencyInjection.Extensions;\n\nnamespace Microsoft.Extensions.DependencyInjection\n{\n    public static class ServiceCollectionExtensions\n    {\n        public static IServiceCollection AddInProcessMessageBus(this IServiceCollection services)\n        {\n            services.AddSingleton<IMediator, Mediator>();\n\n            var assembliesToScan = new[]\n            {\n                Assembly.GetCallingAssembly(),\n                Assembly.GetEntryAssembly(),\n                Assembly.GetExecutingAssembly()\n            }.Distinct().ToArray();\n\n            ConnectImplementationsToTypesClosing(typeof(ICommandHandler<>), services, assembliesToScan, false);\n            ConnectImplementationsToTypesClosing(typeof(IQueryHandler<,>), services, assembliesToScan, false);\n\n            var multiOpenInterfaces = new[]\n            {\n                typeof(ICommandHandler<>),\n                typeof(IQueryHandler<,>)\n            };\n\n            foreach (var multiOpenInterface in multiOpenInterfaces)\n            {\n                var concretions = assembliesToScan\n                    .SelectMany(a => a.DefinedTypes)\n                    .Where(type => type.FindInterfacesThatClose(multiOpenInterface).Any())\n                    .Where(type => type.IsConcrete() && type.IsOpenGeneric())\n                    .ToList();\n\n                foreach (var type in concretions)\n                {\n                    services.AddTransient(multiOpenInterface, type);\n                }\n            }\n\n            return services;\n        }\n\n\n        /// <summary>\n        /// Helper method use to differentiate behavior between request handlers and notification handlers.\n        /// Request handlers should only be added once (so set addIfAlreadyExists to false)\n        /// Notification handlers should all be added (set addIfAlreadyExists to true)\n        /// </summary>\n        private static void ConnectImplementationsToTypesClosing(Type openRequestInterface,\n            IServiceCollection services,\n            IEnumerable<Assembly> assembliesToScan,\n            bool addIfAlreadyExists)\n        {\n            var concretions = new List<Type>();\n            var interfaces = new List<Type>();\n             \n            foreach (var type in assembliesToScan.SelectMany(a => a.DefinedTypes).Where(t => !t.IsOpenGeneric()))\n            {\n                var interfaceTypes = type.FindInterfacesThatClose(openRequestInterface).ToArray();\n                if (!interfaceTypes.Any()) continue;\n\n                if (type.IsConcrete())\n                {\n                    concretions.Add(type);\n                }\n\n                foreach (var interfaceType in interfaceTypes)\n                {\n                    interfaces.Fill(interfaceType);\n                }\n            }\n\n            foreach (var @interface in interfaces)\n            {\n                var exactMatches = concretions.Where(x => x.CanBeCastTo(@interface)).ToList();\n                if (addIfAlreadyExists)\n                {\n                    foreach (var type in exactMatches)\n                    {\n                        services.AddTransient(@interface, type);\n                    }\n                }\n                else\n                {\n                    if (exactMatches.Count > 1)\n                    {\n                        exactMatches.RemoveAll(m => !IsMatchingWithInterface(m, @interface));\n                    }\n\n                    foreach (var type in exactMatches)\n                    {\n                        services.TryAddTransient(@interface, type);\n                    }\n                }\n\n                if (!@interface.IsOpenGeneric())\n                {\n                    AddConcretionsThatCouldBeClosed(@interface, concretions, services);\n                }\n            }\n        }\n\n        private static bool IsMatchingWithInterface(Type handlerType, Type handlerInterface)\n        {\n            if (handlerType == null || handlerInterface == null)\n            {\n                return false;\n            }\n\n            if (handlerType.IsInterface)\n            {\n                if (handlerType.GenericTypeArguments.SequenceEqual(handlerInterface.GenericTypeArguments))\n                {\n                    return true;\n                }\n            }\n            else\n            {\n                return IsMatchingWithInterface(handlerType.GetInterface(handlerInterface.Name), handlerInterface);\n            }\n\n            return false;\n        }\n\n        private static void AddConcretionsThatCouldBeClosed(Type @interface, List<Type> concretions,\n            IServiceCollection services)\n        {\n            foreach (var type in concretions\n                .Where(x => x.IsOpenGeneric() && x.CouldCloseTo(@interface)))\n            {\n                try\n                {\n                    services.TryAddTransient(@interface, type.MakeGenericType(@interface.GenericTypeArguments));\n                }\n                catch (Exception)\n                {\n                    // ignored\n                }\n            }\n        }\n\n        private static bool CouldCloseTo(this Type openConcretion, Type closedInterface)\n        {\n            var openInterface = closedInterface.GetGenericTypeDefinition();\n            var arguments = closedInterface.GenericTypeArguments;\n\n            var concreteArguments = openConcretion.GenericTypeArguments;\n            return arguments.Length == concreteArguments.Length && openConcretion.CanBeCastTo(openInterface);\n        }\n\n        private static bool CanBeCastTo(this Type pluggedType, Type pluginType)\n        {\n            if (pluggedType == null) return false;\n\n            if (pluggedType == pluginType) return true;\n\n            return pluginType.GetTypeInfo().IsAssignableFrom(pluggedType.GetTypeInfo());\n        }\n\n        private static IEnumerable<Type> FindInterfacesThatClose(this Type pluggedType, Type templateType)\n        {\n            return FindInterfacesThatClosesCore(pluggedType, templateType).Distinct();\n        }\n\n\n        private static IEnumerable<Type> FindInterfacesThatClosesCore(Type pluggedType, Type templateType)\n        {\n            if (pluggedType == null) yield break;\n\n            if (!pluggedType.IsConcrete()) yield break;\n\n            if (templateType.GetTypeInfo().IsInterface)\n            {\n                foreach (\n                    var interfaceType in\n                    pluggedType.GetInterfaces()\n                        .Where(type =>\n                            type.GetTypeInfo().IsGenericType && (type.GetGenericTypeDefinition() == templateType)))\n                {\n                    yield return interfaceType;\n                }\n            }\n            else if (pluggedType.GetTypeInfo().BaseType.GetTypeInfo().IsGenericType &&\n                     (pluggedType.GetTypeInfo().BaseType?.GetGenericTypeDefinition() == templateType))\n            {\n                yield return pluggedType.GetTypeInfo().BaseType;\n            }\n\n            if (pluggedType.GetTypeInfo().BaseType == typeof(object)) yield break;\n\n            foreach (var interfaceType in FindInterfacesThatClosesCore(pluggedType.GetTypeInfo().BaseType, templateType)\n            )\n            {\n                yield return interfaceType;\n            }\n        }\n\n        private static bool IsConcrete(this Type type)\n        {\n            return !type.GetTypeInfo().IsAbstract && !type.GetTypeInfo().IsInterface;\n        }\n\n        private static bool IsOpenGeneric(this Type type)\n        {\n            return type.GetTypeInfo().IsGenericTypeDefinition || type.GetTypeInfo().ContainsGenericParameters;\n        }\n\n        private static void Fill<T>(this ICollection<T> list, T value)\n        {\n            if (list.Contains(value)) return;\n            list.Add(value);\n        }\n    }\n}"
  },
  {
    "path": "src/Infrastructure/Persistence/AggregateNotFoundException.cs",
    "content": "using System;\n\nnamespace Infrastructure.Persistence\n{\n    public class AggregateNotFoundException : Exception\n    {\n    }\n}"
  },
  {
    "path": "src/Infrastructure/Persistence/ConcurrencyException.cs",
    "content": "using System;\n\nnamespace Infrastructure.Persistence\n{\n    public class ConcurrencyException : Exception\n    {\n        public ConcurrencyException()\n        {\n        }\n        \n        public ConcurrencyException(string message) : base(message)\n        {\n            \n        }\n    }\n}"
  },
  {
    "path": "src/Infrastructure/Persistence/EventStoreProductRepository.cs",
    "content": "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Domain.ProductContext;\n\nnamespace Infrastructure.Persistence\n{\n    internal class EventStoreProductRepository : IProductRepository\n    {\n        private readonly IEventStore _eventStore;\n        \n        public EventStoreProductRepository(IEventStore eventStore) => _eventStore = eventStore;\n\n        public async Task Save(Product aggregate, CancellationToken cancellationToken)\n        {\n           await _eventStore.SaveEvents(aggregate.Id, aggregate.GetUncommittedChanges(), aggregate.Version);\n           aggregate.MarkChangesAsCommitted();\n        }\n\n        public async Task<Product> Load(Guid id, CancellationToken cancellationToken)\n        {\n            var aggregate = new Product();//lots of ways to do this\n            var e = await _eventStore.GetEventsForAggregate(id);\n            aggregate.LoadsFromHistory(e);\n            return aggregate;\n        }\n    }\n}"
  },
  {
    "path": "src/Infrastructure/Persistence/IEventStore.cs",
    "content": "using System;\nusing System.Collections.Generic;\nusing System.Threading.Tasks;\n\nnamespace Infrastructure.Persistence\n{\n    public interface IEventStore\n    {\n        Task SaveEvents(Guid aggregateId, IEnumerable<object> events, int expectedVersion);\n        Task<List<object>> GetEventsForAggregate(Guid aggregateId);\n    }\n}"
  },
  {
    "path": "src/Infrastructure/Persistence/InMemory/EventStore/InMemoryEventStore.cs",
    "content": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Infrastructure.Messaging.Mediator;\n\nnamespace Infrastructure.Persistence.InMemory.EventStore\n{\n    public class InMemoryEventStore : IEventStore\n    {\n        private readonly IMediator _publisher;\n\n        private struct EventDescriptor\n        {\n            public readonly object EventData;\n            public readonly Guid Id;\n            public readonly int Version;\n\n            public EventDescriptor(Guid id, object eventData, int version)\n            {\n                EventData = eventData;\n                Version = version;\n                Id = id;\n            }\n        }\n\n        public InMemoryEventStore(IMediator publisher)\n        {\n            _publisher = publisher;\n        }\n\n        private readonly Dictionary<Guid, List<EventDescriptor>> _current =\n            new Dictionary<Guid, List<EventDescriptor>>();\n\n        public async Task SaveEvents(Guid aggregateId, IEnumerable<object> events, int expectedVersion)\n        {\n            List<EventDescriptor> eventDescriptors;\n\n            // try to get event descriptors list for given aggregate id\n            // otherwise -> create empty dictionary\n            if (!_current.TryGetValue(aggregateId, out eventDescriptors))\n            {\n                eventDescriptors = new List<EventDescriptor>();\n                _current.Add(aggregateId, eventDescriptors);\n            }\n            // check whether latest event version matches current aggregate version\n            // otherwise -> throw exception\n            else if (eventDescriptors[eventDescriptors.Count - 1].Version != expectedVersion && expectedVersion != -1)\n            {\n                throw new ConcurrencyException();\n            }\n\n            var i = expectedVersion;\n\n            // iterate through current aggregate events increasing version with each processed event\n            foreach (var @event in events)\n            {\n                i++;\n//                @event.Version = i;\n\n                // push event to the event descriptors list for current aggregate\n                eventDescriptors.Add(new EventDescriptor(aggregateId, @event, i));\n\n                // publish current event to the bus for further processing by subscribers\n                await _publisher.PublishAsync(@event);\n            }\n        }\n\n        // collect all processed events for given aggregate and return them as a list\n        // used to build up an aggregate from its history (Domain.LoadsFromHistory)\n        public Task<List<object>> GetEventsForAggregate(Guid aggregateId)\n        {\n            List<EventDescriptor> eventDescriptors;\n\n            if (!_current.TryGetValue(aggregateId, out eventDescriptors))\n            {\n                throw new AggregateNotFoundException();\n            }\n\n            return Task.FromResult(eventDescriptors.Select(desc => desc.EventData).ToList());\n        }\n    }\n}"
  },
  {
    "path": "src/Infrastructure/Persistence/InMemory/ServiceCollectionExtensions.cs",
    "content": "using Domain.ProductContext;\nusing Infrastructure.Persistence.InMemory.EventStore;\nusing Microsoft.Extensions.DependencyInjection;\n\nnamespace Infrastructure.Persistence.InMemory\n{\n    public static class ServiceCollectionExtensions\n    {\n        public static IServiceCollection AddInMemoryEventStorePersistence(this IServiceCollection services)\n        {\n            return services\n                .AddSingleton<IEventStore, InMemoryEventStore>()\n                .AddScoped<IProductRepository, EventStoreProductRepository>();\n        }\n    }\n}"
  },
  {
    "path": "src/Infrastructure/Persistence/Mongo/EventStore/MongoDbEventStore.cs",
    "content": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Infrastructure.Messaging.Mediator;\nusing MongoDB.Driver;\n\nnamespace Infrastructure.Persistence.Mongo.EventStore\n{\n    public class MongoDbEventStore : IEventStore\n    {\n        private readonly IMediator _publisher;\n        private readonly IMongoCollection<EventDescriptor> _collection;\n\n\n        public MongoDbEventStore(IMediator publisher, IMongoDbContext _mongoDbContext)\n        {\n            _publisher = publisher;\n            _collection = _mongoDbContext.GetCollection<EventDescriptor>(\"events\");\n        }\n\n        private class EventDescriptor\n        {\n            public EventDescriptor(Guid id, object eventData, int version)\n            {\n                EventData = eventData;\n                Version = version;\n                AggregateRootId = id;\n                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds();\n            }\n\n            public long Timestamp { get; }\n            \n            public object EventData { get; }\n            public int Version { get; }\n\n            public Guid AggregateRootId { get; }\n        }\n\n        public async Task SaveEvents(Guid aggregateId, IEnumerable<object> events, int expectedVersion)\n        {\n            var last = _collection\n                .AsQueryable()\n                .Where(e => e.AggregateRootId == aggregateId)\n                .OrderBy(e => e.Version)\n                .ThenBy(e => e.Timestamp).LastOrDefault();\n            \n            if (last != null && last.Version != expectedVersion && expectedVersion != -1)\n            {\n                throw new ConcurrencyException();\n            }\n\n            var i = expectedVersion;\n            var eventDescriptors = events.ToList().Select(@event =>\n            {\n                i++;\n                return new EventDescriptor(aggregateId, @event, i);\n            });\n\n            await _collection.InsertManyAsync(eventDescriptors, new InsertManyOptions\n            {\n                IsOrdered = true,\n                BypassDocumentValidation = false\n            });\n\n            await Task.WhenAll(events.Select(@event => _publisher.PublishAsync(@event)));\n        }\n\n        public Task<List<object>> GetEventsForAggregate(Guid aggregateId)\n        {\n            return Task.FromResult(_collection\n                .AsQueryable()\n                .Where(e => e.AggregateRootId == aggregateId)\n                .OrderBy(e => e.Version)\n                .ThenBy(e => e.Timestamp).ToList().Select(descriptor => descriptor.EventData).ToList());\n\n        }\n    }\n}"
  },
  {
    "path": "src/Infrastructure/Persistence/Mongo/IMongoDbContext.cs",
    "content": "using MongoDB.Driver;\n\nnamespace Infrastructure.Persistence.Mongo\n{\n    public interface IMongoDbContext\n    {\n        IMongoCollection<T> GetCollection<T>(string collectionName);\n    }\n}"
  },
  {
    "path": "src/Infrastructure/Persistence/Mongo/MongoDbContext.cs",
    "content": "using MongoDB.Driver;\n\nnamespace Infrastructure.Persistence.Mongo\n{\n\n    public sealed class MongoDbContext : IMongoDbContext\n    {\n        private readonly IMongoDatabase _database;\n\n        public MongoDbContext(IMongoDatabase database)\n        {\n            _database = database;\n        }\n\n        public IMongoCollection<T> GetCollection<T>(string collectionName)\n        {\n            return _database.GetCollection<T>(collectionName);\n        }\n\n    }\n}"
  },
  {
    "path": "src/Infrastructure/Persistence/Mongo/MongoDbProductRepository.cs",
    "content": "using System;\nusing Domain.ProductContext;\nusing Infrastructure.Messaging.Mediator;\n\nnamespace Infrastructure.Persistence.Mongo\n{\n    public class MongoDbProductRepository : MongoDbRepository<Product, Guid>, IProductRepository\n    {\n        public MongoDbProductRepository(IMongoDbContext context, IMediator mediator) : base(mediator, context)\n        {\n        }\n\n        protected override string CollectionName => \"products\";\n    }\n}"
  },
  {
    "path": "src/Infrastructure/Persistence/Mongo/MongoDbProvider.cs",
    "content": "using MongoDB.Driver;\n\nnamespace Infrastructure.Persistence.Mongo\n{\n    public class MongoDbProvider\n    {\n        public static IMongoDatabase Provide(MongoSettings settings)\n        {\n            //var client = new MongoClient(settings.Value.ConnectionString);\n\n            MongoClientSettings clientSettings = new MongoClientSettings();\n            clientSettings.Server = new MongoServerAddress(settings.Host, 10255);\n            clientSettings.UseTls = settings.UseSsl;\n            if (settings.UseSsl)\n            {\n                clientSettings.SslSettings = new SslSettings();\n                clientSettings.SslSettings.EnabledSslProtocols = settings.EnabledSslProtocols;\n            }\n\n            MongoIdentity identity = new MongoInternalIdentity(settings.Database, settings.UserName);\n            MongoIdentityEvidence evidence = new PasswordEvidence(settings.Password);\n\n            clientSettings.Credential = new MongoCredential(\"SCRAM-SHA-1\", identity, evidence);\n\n            MongoClient client = new MongoClient(clientSettings);\n\n            return client.GetDatabase(settings.Database);\n        }\n    }\n}"
  },
  {
    "path": "src/Infrastructure/Persistence/Mongo/MongoDbRepository.cs",
    "content": "using System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Domain;\nusing Domain.Abstraction;\nusing Infrastructure.Messaging.Mediator;\nusing MongoDB.Driver;\nusing MongoDB.Driver.Linq;\n\nnamespace Infrastructure.Persistence.Mongo\n{\n    // todo: https://github.com/NEventStore/NEventStore.Persistence.MongoDB review the impl\n    public abstract class MongoDbRepository<TAggregate, TKey> : IRepository<TAggregate, TKey>\n        where TAggregate : AggregateRoot<TKey>\n    {\n        protected abstract string CollectionName { get; }\n\n        private readonly IMediator _mediator;\n        private readonly IMongoCollection<TAggregate> _collection;\n        \n        protected MongoDbRepository(IMediator mediator,IMongoDbContext context )\n        {\n            _mediator = mediator;\n            _collection = context.GetCollection<TAggregate>(CollectionName);\n        }\n        \n        public virtual async Task Save(TAggregate aggregate, CancellationToken cancellationToken)\n        {\n            var existing = await _collection.AsQueryable().Where(p => p.Id.Equals(aggregate.Id)).FirstOrDefaultAsync(cancellationToken);\n            if (existing != null)\n            {\n                if (existing.Version > aggregate.Version)\n                {\n                    throw new ConcurrencyException();\n                }\n\n                await _collection.ReplaceOneAsync(c => c.Id.Equals(aggregate.Id), aggregate, new UpdateOptions()\n                {\n                    IsUpsert = true\n                }, cancellationToken);\n            }\n            else\n            {\n                await _collection.InsertOneAsync(aggregate, new InsertOneOptions\n                {\n                    BypassDocumentValidation = false\n                }, cancellationToken);\n            }\n            \n            // todo: find a way to prevent inconsistency between state and domain events\n            await DispatchDomainEventsAsync(aggregate, cancellationToken);\n            \n        }\n        protected async Task DispatchDomainEventsAsync(TAggregate aggregateRoot, CancellationToken cancellationToken)\n        {\n            var domainEvents = aggregateRoot.GetUncommittedChanges();\n            aggregateRoot.MarkChangesAsCommitted();\n            \n            await Task.WhenAll(domainEvents\n                .Select(async domainEvent => await _mediator.PublishAsync(domainEvent, cancellationToken)));\n        }\n        \n        public virtual Task<TAggregate> Load(TKey id, CancellationToken cancellationToken)\n        {\n            return _collection.AsQueryable().Where(p => p.Id.Equals(id)).FirstOrDefaultAsync(cancellationToken);\n        }\n    }\n}"
  },
  {
    "path": "src/Infrastructure/Persistence/Mongo/MongoSettings.cs",
    "content": "using System.Security.Authentication;\n\nnamespace Infrastructure.Persistence.Mongo\n{\n    public class MongoSettings\n    {\n        //public string ConnectionString { get; set; }\n        public int Port { get; set; } = 10255;\n        public string Host { get; set; }\n        public bool UseSsl { get; set; } = true;\n        public string Database { get; set; }\n        public SslProtocols EnabledSslProtocols { get; set; } = SslProtocols.Tls12;\n        public string Password { get; internal set; }\n        public string UserName { get; internal set; }\n    }\n}"
  },
  {
    "path": "src/Infrastructure/Persistence/Mongo/ServiceCollectionExtensions.cs",
    "content": "using Domain.ProductContext;\nusing Infrastructure.Persistence.Mongo.EventStore;\nusing Microsoft.Extensions.Configuration;\nusing Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.Options;\n\nnamespace Infrastructure.Persistence.Mongo\n{\n    public static class ServiceCollectionExtensions\n    {\n        public static IServiceCollection AddMongoDbPersistence(this IServiceCollection services,\n            IConfiguration configuration)\n        {\n            return services\n                .Configure<MongoSettings>(configuration.GetSection(\"MongoDb\"))\n                .AddSingleton(c => MongoDbProvider.Provide(c.GetRequiredService<IOptions<MongoSettings>>().Value))\n                .AddSingleton<IMongoDbContext, MongoDbContext>()\n                .AddScoped<IProductRepository, MongoDbProductRepository>();\n        }\n\n        public static IServiceCollection AddMongoDbEventStorePersistence(this IServiceCollection services,\n            IConfiguration configuration)\n        {\n            return services\n                .Configure<MongoSettings>(configuration.GetSection(\"MongoDb\"))\n                .AddSingleton(c => MongoDbProvider.Provide(c.GetRequiredService<IOptions<MongoSettings>>().Value))\n                .AddSingleton<IMongoDbContext, MongoDbContext>()\n                .AddSingleton<IEventStore, MongoDbEventStore>()\n                .AddScoped<IProductRepository, EventStoreProductRepository>();\n        }\n    }\n}"
  },
  {
    "path": "src/Infrastructure/ServiceCollectionExtensions.cs",
    "content": "using Infrastructure.Persistence.InMemory;\nusing Infrastructure.Persistence.Mongo;\nusing Microsoft.Extensions.Configuration;\nusing Microsoft.Extensions.DependencyInjection;\n\nnamespace Infrastructure\n{\n    public static class ServiceCollectionExtensions\n    {\n        public static IServiceCollection AddInfrastructure(this IServiceCollection services,\n            IConfiguration configuration)\n        {\n            return services\n                .AddInMemoryEventStorePersistence()\n//                .AddMongoDbPersistence(configuration)\n//                .AddMongoDbEventStorePersistence(configuration)\n                .AddInProcessMessageBus();\n        }\n    }\n}"
  },
  {
    "path": "src/WebApi/Extensions/ApplicationBuilderExtensions.cs",
    "content": "﻿using System.Reflection;\nusing System.Threading.Tasks;\nusing Microsoft.AspNetCore.Builder;\nusing Microsoft.AspNetCore.Hosting;\nusing Microsoft.AspNetCore.Http;\nusing Microsoft.Extensions.Configuration;\n\nnamespace WebApi.Extensions\n{\n    public static class ApplicationBuilderExtensions\n    {\n        public static IApplicationBuilder UseAspNetInfrastructure(this IApplicationBuilder app,\n            IWebHostEnvironment hostingEnvironment,\n            IConfiguration configuration)\n        {\n            return app.UseResponseCompression()\n                .UseApplicationHeaders(hostingEnvironment, configuration)\n                .UseSwaggerConf()\n                .UseMvc()\n                .UseHsts();\n        }\n        \n        public static IApplicationBuilder UseSwaggerConf(this IApplicationBuilder app)\n        {\n            return app\n                .UseSwagger()\n                .UseSwaggerUI(c =>\n                {\n                    c.RoutePrefix = \"\";\n                    c.SwaggerEndpoint(\"/swagger/v1/swagger.json\", \"PimReadProjector API Swagger v1\");\n                });\n        }\n\n        public static IApplicationBuilder UseApplicationHeaders(this IApplicationBuilder app,\n            IWebHostEnvironment hostingEnvironment,\n            IConfiguration configuration)\n        {\n            var appVersion = configuration[\"APP_VERSION\"] ??\n                             Assembly.GetExecutingAssembly().GetCustomAttribute<AssemblyFileVersionAttribute>().Version;\n\n            return app.Use(async (context, func) =>\n            {\n                context.Response.OnStarting(state =>\n                {\n                    var httpContext = (HttpContext) state;\n\n                    httpContext.Response.Headers.Add(\"X-Environment\", new[] {hostingEnvironment.EnvironmentName});\n                    httpContext.Response.Headers.Add(\"X-Version\", new[] {appVersion});\n                    return Task.FromResult(0);\n                }, context);\n\n                await func.Invoke();\n            });\n        }\n    }\n}"
  },
  {
    "path": "src/WebApi/Extensions/OriginalNameCamelCaseContractResolver.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Newtonsoft.Json;\nusing Newtonsoft.Json.Serialization;\n\nnamespace WebApi.Extensions\n{\n    internal class OriginalNameCamelCaseContractResolver : CamelCasePropertyNamesContractResolver\n    {\n        private readonly string[] _namespaces;\n\n        public OriginalNameCamelCaseContractResolver(Type[] types)\n            : this(types.Select(t => t.Namespace).ToArray())\n        {\n        }\n\n        public OriginalNameCamelCaseContractResolver(string[] namespaces)\n        {\n            _namespaces = namespaces;\n        }\n\n        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)\n        {\n            var list = base.CreateProperties(type, memberSerialization);\n            if (!_namespaces.Any(x => type.Namespace.StartsWith(x)))\n            {\n                return list;\n            }\n\n            foreach (var prop in list)\n            {\n                prop.PropertyName = NamingStrategy.GetPropertyName(prop.UnderlyingName, false);\n            }\n\n            return list;\n        }\n    }\n}"
  },
  {
    "path": "src/WebApi/Extensions/ServiceCollectionExtensions.cs",
    "content": "using System;\nusing System.IO;\nusing System.Reflection;\nusing FluentValidation.AspNetCore;\nusing Microsoft.AspNetCore.Builder;\nusing Microsoft.AspNetCore.Mvc;\nusing Microsoft.Extensions.DependencyInjection;\nusing Swashbuckle.AspNetCore.Swagger;\n\nnamespace WebApi.Extensions\n{\n    public static class ServiceCollectionExtensions\n    {\n        public static IServiceCollection AddAspNetInfrastructure(this IServiceCollection services)\n        {\n            services\n                .AddSwaggerGen(c =>\n                {\n                    c.SwaggerDoc(\"v1\", new Info\n                    {\n                        Title = \"Pim translation API Swagger\",\n                        Version = \"v1\"\n                    });\n\n                    var xmlFile = $\"{Assembly.GetExecutingAssembly().GetName().Name}.XML\";\n                    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);\n                    if (File.Exists(xmlPath))\n                    {\n                        c.IncludeXmlComments(xmlPath);\n                    }\n                })\n                .AddResponseCompression()\n                .AddMvc()                \n                .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)\n                .AddFluentValidation(fv => fv.RegisterValidatorsFromAssembly(Assembly.GetExecutingAssembly()));\n            return services;\n        }\n    }\n}"
  },
  {
    "path": "src/WebApi/Program.cs",
    "content": "﻿using System.Threading.Tasks;\nusing Infrastructure;\nusing Infrastructure.Logging;\nusing Microsoft.AspNetCore;\nusing Microsoft.AspNetCore.Hosting;\nusing Microsoft.Extensions.Hosting;\n\nnamespace WebApi\n{\n    public class Program\n    {\n        public static Task Main(string[] args) => CreateHostBuilder(args).Build().RunAsync();\n\n        public static IHostBuilder CreateHostBuilder(string[] args) =>\n            Host.CreateDefaultBuilder(args)\n                .ConfigureWebHostDefaults(webBuilder =>\n                {\n                    webBuilder\n                        .UseStartup<Startup>()\n                        .ConfigureLoggingPlumbing()\n                        .CaptureStartupErrors(true);\n                });\n    }\n}"
  },
  {
    "path": "src/WebApi/Properties/launchSettings.json",
    "content": "﻿{\n  \"$schema\": \"http://json.schemastore.org/launchsettings.json\",\n  \"iisSettings\": {\n    \"windowsAuthentication\": false, \n    \"anonymousAuthentication\": true, \n    \"iisExpress\": {\n      \"applicationUrl\": \"http://localhost:58681\",\n      \"sslPort\": 44388\n    }\n  },\n  \"profiles\": {\n    \"IIS Express\": {\n      \"commandName\": \"IISExpress\",\n      \"launchBrowser\": true,\n      \"launchUrl\": \"api/values\",\n      \"environmentVariables\": {\n        \"ASPNETCORE_ENVIRONMENT\": \"Development\"\n      }\n    },\n    \"WebApi\": {\n      \"commandName\": \"Project\",\n      \"launchBrowser\": true,\n      \"launchUrl\": \"api/values\",\n      \"applicationUrl\": \"https://localhost:5001;http://localhost:5000\",\n      \"environmentVariables\": {\n        \"ASPNETCORE_ENVIRONMENT\": \"Development\"\n      }\n    }\n  }\n}"
  },
  {
    "path": "src/WebApi/Startup.cs",
    "content": "﻿using Infrastructure; \nusing Microsoft.AspNetCore.Builder;\nusing Microsoft.AspNetCore.Hosting;\nusing Microsoft.Extensions.Configuration;\nusing Microsoft.Extensions.DependencyInjection;\nusing WebApi.Extensions;\n\nnamespace WebApi\n{\n    public class Startup\n    {\n        public Startup(IConfiguration configuration)\n        {\n            Configuration = configuration;\n        }\n\n        public IConfiguration Configuration { get; }\n\n        public void ConfigureServices(IServiceCollection services)\n        {\n            services\n                .AddInfrastructure(Configuration)\n                .AddAspNetInfrastructure();\n        }\n\n        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)\n        {\n            app.UseAspNetInfrastructure(env, Configuration);\n        }\n    }\n}"
  },
  {
    "path": "src/WebApi/UseCases/AddContentToProduct/AddContentToProductCommandValidator.cs",
    "content": "using Application.UseCases.AddContentToProduct;\nusing FluentValidation;\n\nnamespace WebApi.UseCases.AddContentToProduct\n{\n    public class AddContentToProductCommandValidator: AbstractValidator<AddContentToProductCommand> {\n        public AddContentToProductCommandValidator() {\n            RuleFor(x => x.Description).NotNull();\n            RuleFor(x => x.Title).NotNull();\n            RuleFor(x => x.AttributeId).NotNull();\n            RuleFor(x => x.ProductId).NotNull(); \n            RuleFor(x => x.AttributeValueId).NotNull(); \n        }\n    }\n}"
  },
  {
    "path": "src/WebApi/UseCases/AddContentToProduct/ProductController.cs",
    "content": "using System.Threading;\nusing System.Threading.Tasks;\nusing Application.UseCases.AddContentToProduct;\nusing Infrastructure.Messaging.Mediator;\nusing Microsoft.AspNetCore.Mvc;\n\nnamespace WebApi.UseCases.AddContentToProduct\n{\n    [Route(\"api/[controller]\")]\n    [ApiController]\n    public class ProductsController : ControllerBase\n    {\n        private readonly IMediator _mediator;\n\n        public ProductsController(IMediator mediator) => _mediator = mediator;\n\n        // POST api/products\n        [HttpPost]\n        public async Task Post([FromBody] AddContentToProductCommand command, CancellationToken cancellationToken)\n        {\n            await _mediator.SendAsync(command, cancellationToken);\n        }\n    }\n}"
  },
  {
    "path": "src/WebApi/UseCases/CreateProduct/CreateProductCommandValidator.cs",
    "content": "using Application.UseCases.CreateProduct;\nusing FluentValidation;\n\nnamespace WebApi.UseCases.CreateProduct\n{\n    public class CreateProductCommandValidator : AbstractValidator<CreateProductCommand>\n    {\n        public CreateProductCommandValidator()\n        {\n            RuleFor(x => x.BrandId).NotNull();\n            RuleFor(x => x.CategoryId).NotNull();\n            RuleFor(x => x.ProductCode).NotNull();\n        }\n    }\n}"
  },
  {
    "path": "src/WebApi/UseCases/CreateProduct/ProductsController.cs",
    "content": "using System.Threading;\nusing System.Threading.Tasks;\nusing Application.UseCases.CreateProduct;\nusing Infrastructure.Messaging.Mediator;\nusing Microsoft.AspNetCore.Mvc;\n\nnamespace WebApi.UseCases.CreateProduct\n{\n    [Route(\"api/[controller]\")]\n    [ApiController]\n    public class ProductsController : ControllerBase\n    {\n        private readonly IMediator _mediator;\n\n        public ProductsController(IMediator mediator) => _mediator = mediator;\n\n        // POST api/products\n        [HttpPost]\n        public async Task Post([FromBody] CreateProductCommand command, CancellationToken cancellationToken)\n        {\n            await _mediator.SendAsync(command, cancellationToken);\n        }\n    }\n}"
  },
  {
    "path": "src/WebApi/WebApi.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk.Web\">\n\n    <PropertyGroup>\n        <TargetFramework>netcoreapp3.0</TargetFramework>\n        <LangVersion>latest</LangVersion>\n    </PropertyGroup>\n\n    <ItemGroup>\n        <PackageReference Include=\"FluentValidation.AspNetCore\" Version=\"8.5.0\" />\n    </ItemGroup>\n\n    <ItemGroup>\n      <Content Update=\"appsettings.Development.json\">\n        <DependentUpon>appsettings.json</DependentUpon>\n      </Content>\n      <Content Update=\"appsettings.Production.json\">\n        <DependentUpon>appsettings.json</DependentUpon>\n      </Content>\n      <Content Update=\"appsettings.Staging.json\">\n        <DependentUpon>appsettings.json</DependentUpon>\n      </Content>\n    </ItemGroup>\n\n    <ItemGroup>\n      <ProjectReference Include=\"..\\Application\\Application.csproj\" />\n      <ProjectReference Include=\"..\\Infrastructure\\Infrastructure.csproj\" />\n    </ItemGroup>\n\n</Project>\n"
  },
  {
    "path": "src/WebApi/app.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<configuration>\n  <runtime>\n    <gcServer enabled=\"true\"/>\n  </runtime>\n</configuration>"
  },
  {
    "path": "src/WebApi/appsettings.Development.json",
    "content": "{\n  \"Logging\": {\n    \"LogLevel\": {\n      \"Default\": \"Debug\",\n      \"System\": \"Information\",\n      \"Microsoft\": \"Information\"\n    }\n  }\n}\n"
  },
  {
    "path": "src/WebApi/appsettings.Production.json",
    "content": "{\n  \"Serilog\": {\n    \"Console\": false,\n    \"MinimumLevel\": {\n      \"Default\": \"Error\"\n    }\n  }\n}"
  },
  {
    "path": "src/WebApi/appsettings.Staging.json",
    "content": "{\n  \"Serilog\": {\n    \"Console\": false,\n    \"MinimumLevel\": {\n      \"Default\": \"Error\"\n    }\n  }\n}"
  },
  {
    "path": "src/WebApi/appsettings.json",
    "content": "{\n  \"Logging\": {\n    \"LogLevel\": {\n      \"Default\": \"Warning\"\n    }\n  },\n  \"Serilog\": {\n    \"GraylogIp\": \"\",\n    \"GraylogPort\": 0,\n    \"Console\": true,\n    \"FacilityName\": \"service-name\",\n    \"MinimumLevel\": {\n      \"Default\": \"Verbose\",\n      \"Override\": {\n        \"Microsoft\": \"Information\",\n        \"System\": \"Warning\",\n        \"System.Net.Http.HttpClient\": \"Warning\"\n      }\n    }\n  },\n  \"AllowedHosts\": \"*\"\n}\n"
  },
  {
    "path": "test/Application.Tests/Application.Tests.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n\n    <PropertyGroup>\n        <TargetFramework>netcoreapp3.0</TargetFramework>\n\n        <IsPackable>false</IsPackable>\n    </PropertyGroup>\n\n    <ItemGroup>\n        <PackageReference Include=\"FluentValidation.AspNetCore\" Version=\"8.5.0\" />\n        <PackageReference Include=\"Microsoft.NET.Test.Sdk\" Version=\"16.3.0\" />\n        <PackageReference Include=\"xunit\" Version=\"2.4.1\" />\n        <PackageReference Include=\"xunit.runner.visualstudio\" Version=\"2.4.1\" />\n    </ItemGroup>\n\n    <ItemGroup>\n      <ProjectReference Include=\"..\\..\\src\\Application\\Application.csproj\" />\n      <ProjectReference Include=\"..\\..\\src\\Infrastructure\\Infrastructure.csproj\" />\n      <ProjectReference Include=\"..\\TestBase\\TestBase.csproj\" />\n    </ItemGroup>\n\n</Project>\n"
  },
  {
    "path": "test/Application.Tests/CommandHandlerTestBase.cs",
    "content": "using Microsoft.Extensions.DependencyInjection;\nusing TestBase;\n\nnamespace Application.Tests\n{\n    public abstract class CommandHandlerTestBase: TestBaseWithIoC\n    {\n        protected CommandHandlerTestBase()\n        {\n            ConfigureServices(services =>\n            {\n                services\n                    .AddInProcessMessageBus();\n            }).\n            Build();\n        } \n    }\n}"
  },
  {
    "path": "test/Application.Tests/CreateProductCommandHandlerTests.cs",
    "content": "using System.Threading;\nusing System.Threading.Tasks;\nusing Application.UseCases.CreateProduct;\nusing Domain.ProductContext;\nusing Xunit;\n\nnamespace Application.Tests\n{\n    public class CreateProductCommandHandlerTests : CommandHandlerTestBase\n    {\n        private readonly CreateProductCommandHandler _sut;\n        private readonly IProductRepository _repository;\n\n        public CreateProductCommandHandlerTests()\n        {\n            _repository = FakeAndRegister<IProductRepository>();\n            _sut = new CreateProductCommandHandler(_repository);\n        }\n\n        [Fact]\n        public async Task Should_Persist_Created_Product()\n        {\n            // Given\n            var expectedCategoryId = Random<int>();\n            var expectedBrandId = Random<int>();\n            var expectedProductCode = Random<string>();\n\n            // When\n            await _sut.Handle(new CreateProductCommand(expectedCategoryId, expectedBrandId, expectedProductCode),\n                CancellationToken.None);\n\n            // Then\n            Verify(() => _repository.Save(Matches<Product>(c => c.Category.Id == expectedCategoryId\n                                                                && c.Brand.Id == expectedBrandId\n                                                                && c.Code == expectedProductCode),\n                Ignore<CancellationToken>()));\n        }\n    }\n}"
  },
  {
    "path": "test/Domain.Specs/Domain.Specs.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n\n    <PropertyGroup>\n        <TargetFramework>netcoreapp3.0</TargetFramework>\n\n        <IsPackable>false</IsPackable>\n    </PropertyGroup>\n\n    <ItemGroup>\n        <PackageReference Include=\"FluentValidation.AspNetCore\" Version=\"8.5.0\" />\n        <PackageReference Include=\"Microsoft.NET.Test.Sdk\" Version=\"16.3.0\" />\n        <PackageReference Include=\"xunit\" Version=\"2.4.1\" />\n        <PackageReference Include=\"xunit.runner.visualstudio\" Version=\"2.4.1\" />\n    </ItemGroup>\n\n    <ItemGroup>\n      <ProjectReference Include=\"..\\TestBase\\TestBase.csproj\" />\n    </ItemGroup>\n\n\n</Project>\n"
  },
  {
    "path": "test/Domain.Specs/ProductSpecs/WhenContentAddedToProduct.cs",
    "content": "using System;\nusing System.Linq;\nusing Domain.ProductContext;\nusing Domain.ProductContext.Events;\nusing TestBase;\nusing Xunit;\n\nnamespace Domain.Specs.ProductSpecs\n{\n    public class WhenContentAddedToProduct : SpecBase<Product>\n    {\n        [Fact]\n        public void Content_Should_Be_Added()\n        {\n            var productId = Random<Guid>();\n            var title = Random<string>();\n            var description = Random<string>();\n            var attributeId = Random<int>();\n            var attributeValueId = Random<int>();\n\n            var @event = new ContentAddedToProduct(\n                productId,\n                title,\n                description, new AttributeRef(attributeId, attributeValueId));\n\n            ScenarioForExisting()\n                .Given(\n                    () => Product.Create(productId, Random<int>(), Random<int>(), Random<string>()))\n                .When(\n                    product => product.AddContent(title, description, new AttributeRef(attributeId, attributeValueId))\n                )\n                .Then(@event)\n                .AlsoAssert(\n                    product => product.Contents\n                        .Any(x => x.Title == title)\n                );\n        }\n\n        [Fact]\n        public void Given_Product_Has_DifferentType_Attribute_Then_Business_Exception_Should_Be_Thrown()\n        {\n            ScenarioForExisting()\n                .Given(\n                    () =>\n                    {\n                        var aggregate = Product.Create(Random<Guid>(), Random<int>(), Random<int>(), Random<string>());\n                        aggregate.AddContent(Random<string>(), Random<string>(),\n                            new AttributeRef(Random<int>(), Random<int>()));\n                        return aggregate;\n                    })\n                .When(\n                    product => product.AddContent(Random<string>(), Random<string>(),\n                        new AttributeRef(Random<int>(), Random<int>()))\n                )\n                .ThenThrows<BusinessException>(\"Given attribute type should belong to any content of product as slicer\");\n        }\n\n        [Fact]\n        public void Given_Product_Has_Same_Attribute_Then_Business_Exception_Should_Be_Thrown()\n        {\n            var anAttribute = new AttributeRef(Random<int>(), Random<int>());\n            ScenarioForExisting()\n                .Given(\n                    () =>\n                    {\n                        var aggregate = Product.Create(Random<Guid>(), Random<int>(), Random<int>(), Random<string>());\n                        aggregate.AddContent(Random<string>(), Random<string>(), anAttribute);\n                        return aggregate;\n                    })\n                .When(\n                    product => product.AddContent(Random<string>(), Random<string>(), anAttribute)\n                )\n                .ThenThrows<BusinessException>(\"Same content already exists with given attribute\");\n        }\n    }\n}"
  },
  {
    "path": "test/Domain.Specs/ProductSpecs/WhenCreated.cs",
    "content": "using System;\nusing Domain.ProductContext;\nusing Domain.ProductContext.Events;\nusing TestBase;\nusing Xunit;\n\nnamespace Domain.Specs.ProductSpecs\n{\n    public class WhenCreated : SpecBase<Product>\n    {\n        [Fact]\n        public void Aggregate_Should_Be_Created_And_Publish_ProductCreated_Event()\n        {\n            var productId = Random<Guid>();\n            var brandId = Random<int>();\n            var productCode = Random<string>();\n            var categoryId = Random<int>();\n\n            var productCreated = new ProductCreated(\n                productId,\n                productCode,\n                brandId, categoryId);\n\n            ScenarioFor(\n                    () => Product.Create(productId, categoryId, brandId, productCode)\n                )\n                .When(product => { })\n                .Then(productCreated);\n        }\n    }\n}"
  },
  {
    "path": "test/Domain.Specs/ProductSpecs/WhenProductApproved.cs",
    "content": "using System;\nusing Domain.ProductContext;\nusing Domain.ProductContext.Events;\nusing TestBase;\nusing Xunit;\n\nnamespace Domain.Specs.ProductSpecs\n{\n    public class WhenProductApproved : SpecBase<Product>\n    {\n        [Fact]\n        public void Given_Product_Has_No_Content_Business_Exception_Should_Be_Thrown()\n        {\n            var productId = Random<Guid>();\n\n            ScenarioForExisting()\n                .Given(\n                    () =>\n                    {\n                        var aggregate = Product.Create(productId, Random<int>(), Random<int>(), Random<string>());\n                        return aggregate;\n                    })\n                .When(\n                    product => product.Approve())\n                .ThenThrows<BusinessException>(\"Product must have at least one content\");\n        }\n\n        [Fact]\n        public void Given_Product_Has_No_Variant_Business_Exception_Should_Be_Thrown()\n        {\n            var productId = Random<Guid>();\n\n            ScenarioForExisting()\n                .Given(\n                    () =>\n                    {\n                        var aggregate = Product.Create(productId, Random<int>(), Random<int>(), Random<string>());\n                        aggregate.AddContent(Random<string>(), Random<string>(),\n                            new AttributeRef(Random<int>(), Random<int>()));\n                        return aggregate;\n                    })\n                .When(\n                    product => product.Approve())\n                .ThenThrows<BusinessException>(\"Product must have at least one variant\");\n        }\n\n        [Fact]\n        public void Given_Product_Has_No_Image_Business_Exception_Should_Be_Thrown()\n        {\n            var productId = Random<Guid>();\n\n            ScenarioForExisting()\n                .Given(\n                    () =>\n                    {\n                        var aggregate = Product.Create(productId, Random<int>(), Random<int>(), Random<string>());\n                        var slicerAttribute = new AttributeRef(Random<int>(), Random<int>());\n                        aggregate.AddContent(Random<string>(), Random<string>(), slicerAttribute);\n                        aggregate.AddVariant(Random<string>(), slicerAttribute,\n                            new AttributeRef(Random<int>(), Random<int>()));\n                        return aggregate;\n                    })\n                .When(\n                    product => product.Approve())\n                .ThenThrows<BusinessException>(\"Product must have at least one image\");\n        }\n\n        [Fact]\n        public void Product_Should_Be_Approved()\n        {\n            var productId = Random<Guid>();\n            var @event = new ProductApproved(productId);\n\n            ScenarioForExisting()\n                .Given(\n                    () =>\n                    {\n                        var aggregate = Product.Create(productId, Random<int>(), Random<int>(), Random<string>());\n                        var slicerAttribute = new AttributeRef(Random<int>(), Random<int>());\n                        aggregate.AddContent(Random<string>(), Random<string>(), slicerAttribute);\n                        var varianterAttribute = new AttributeRef(Random<int>(), Random<int>());\n                        aggregate.AddVariant(Random<string>(), slicerAttribute, varianterAttribute);\n                        aggregate.AssignImage(Random<ImageRef>(), varianterAttribute);\n                        return aggregate;\n                    })\n                .When(\n                    product => product.Approve())\n                .Then(@event)\n                .AlsoAssert(product => product.IsApproved);\n        }\n    }\n}"
  },
  {
    "path": "test/Domain.Specs/ProductSpecs/WhenVariantAddedToProduct.cs",
    "content": "using System;\nusing System.Linq;\nusing Domain.ProductContext;\nusing Domain.ProductContext.Events;\nusing TestBase;\nusing Xunit;\n\nnamespace Domain.Specs.ProductSpecs\n{\n    public class WhenVariantAddedToProduct : SpecBase<Product>\n    {\n        [Fact]\n        public void Variant_Should_Be_Added()\n        {\n            var slicerAttributeId = Random<int>();\n            var slicerAttributeValueId = Random<int>();\n            var productId = Random<Guid>();\n            var barcode = Random<String>();\n            var varianterAttributeId = Random<int>();\n            var varianterAttributeValueId = Random<int>();\n            \n            var @event = new VariantAddedToProduct(productId, barcode, \n                new AttributeRef(slicerAttributeId, slicerAttributeValueId),\n                new AttributeRef(varianterAttributeId,  varianterAttributeValueId) );\n\n            ScenarioForExisting()\n                .Given(\n                    () =>\n                    {\n                        var aggregate = Product.Create(productId, Random<int>(), Random<int>(), Random<string>());\n                        aggregate.AddContent(Random<string>(), Random<string>(), new AttributeRef(slicerAttributeId, slicerAttributeValueId));\n                        return aggregate;\n                    })\n                .When\n                (\n                    product => product.AddVariant(barcode,\n                        new AttributeRef(slicerAttributeId, slicerAttributeValueId), \n                        new AttributeRef(varianterAttributeId, varianterAttributeValueId))\n                )\n                .Then(@event)\n                .AlsoAssert(\n                    product => product.Contents.SelectMany(c => c.Variants)\n                        .Any(x => x.Barcode == barcode)\n                );\n        }\n        \n        [Fact]\n        public void Given_Product_Has_No_Content_With_Given_Slicer_Should_Throw_Business_Exception()\n        {\n            var slicerAttributeId = Random<int>();\n            var slicerAttributeValueId = Random<int>();\n             var barcode = Random<String>();\n            var varianterAttributeId = Random<int>();\n            var varianterAttributeValueId = Random<int>();\n             \n            ScenarioForExisting()\n                .Given(\n                    () => Product.Create(Random<Guid>(), Random<int>(), Random<int>(), Random<string>()))\n                .When\n                (\n                    product => product.AddVariant(barcode,\n                        new AttributeRef(slicerAttributeId, slicerAttributeValueId), \n                        new AttributeRef(varianterAttributeId, varianterAttributeValueId))\n                )\n                .ThenThrows<BusinessException>(\"No content found with given slicer attribute.\");\n        }\n    }\n}"
  },
  {
    "path": "test/Infrastructure.Tests/Infrastructure.Tests.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n\n    <PropertyGroup>\n        <TargetFramework>netcoreapp3.0</TargetFramework>\n\n        <IsPackable>false</IsPackable>\n    </PropertyGroup>\n\n    <ItemGroup>\n        <PackageReference Include=\"FluentValidation.AspNetCore\" Version=\"8.5.0\" />\n        <PackageReference Include=\"Microsoft.NET.Test.Sdk\" Version=\"16.3.0\" />\n        <PackageReference Include=\"xunit\" Version=\"2.4.1\" />\n        <PackageReference Include=\"xunit.runner.visualstudio\" Version=\"2.4.1\" />\n    </ItemGroup>\n\n    <ItemGroup>\n      <ProjectReference Include=\"..\\..\\src\\Infrastructure\\Infrastructure.csproj\" />\n      <ProjectReference Include=\"..\\TestBase\\TestBase.csproj\" />\n    </ItemGroup>\n\n</Project>\n"
  },
  {
    "path": "test/Infrastructure.Tests/MediatorTests.cs",
    "content": "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Application;\nusing Infrastructure.Messaging.Mediator;\nusing Microsoft.Extensions.DependencyInjection;\nusing TestBase;\nusing Xunit;\n\nnamespace Infrastructure.Tests\n{\n    public class MediatorTests : TestBaseWithIoC\n    {\n        internal static Guid Command_Should_Be_Handled_Test_Assertion = Guid.Empty;\n        public MediatorTests()\n        {\n            ConfigureServices(services =>\n                {\n                    services\n                        .AddInProcessMessageBus();\n                }).\n                Build();\n        }\n\n        [Fact]\n        public async Task Command_Should_Be_Handled()\n        {\n           var bus = GetRequiredService<IMediator>();\n\n           var newGuid = Guid.NewGuid();\n           await bus.SendAsync(new TestCommand(newGuid));\n           \n           Assert.Equal(newGuid, Command_Should_Be_Handled_Test_Assertion);\n        }\n        \n    }\n    \n    public class TestCommand\n    {\n        public TestCommand(Guid test)\n        {\n            Test = test;\n        }\n\n        public Guid Test { get; }    \n    }\n\n    public class TestCommandHandler : ICommandHandler<TestCommand>\n    {\n        public Task Handle(TestCommand message, CancellationToken cancellationToken)\n        {\n            MediatorTests.Command_Should_Be_Handled_Test_Assertion = message.Test;\n            \n            return Task.CompletedTask;\n        }\n    }\n}"
  },
  {
    "path": "test/TestBase/InMemoryDatabaseFixture.cs",
    "content": "using System;\nusing System.Collections.Generic;\nusing System.Data;\nusing System.Linq.Expressions;\nusing ServiceStack.OrmLite;\nusing ServiceStack.OrmLite.Legacy;\nusing ServiceStack.OrmLite.Sqlite;\n\nnamespace TestBase\n{\n    public class InMemoryDatabaseFixture : IDisposable\n    {\n        private readonly OrmLiteConnectionFactory _dbFactory =\n            new OrmLiteConnectionFactory(\":memory:\", SqliteOrmLiteDialectProvider.Instance);\n\n        private IDbConnection _db;\n\n        public IDbConnection OpenConnection() => _dbFactory.OpenDbConnection();\n\n        public void Insert<T>(IEnumerable<T> items, string tableName)\n        {\n            _db = _db ?? OpenConnection();\n            _db.DropAndCreateTable<T>(tableName);\n            foreach (var item in items)\n            {\n                _db.Insert(tableName, item);\n            }\n        }\n\n        public void Dispose()\n        {\n            _db?.Dispose();\n            _db = null;\n        }\n    }\n\n    public static class GenericTableExtensions\n    {\n        static object ExecWithAlias<T>(string table, Func<object> fn)\n        {\n            var modelDef = typeof(T).GetModelMetadata();\n            lock (modelDef)\n            {\n                var hold = modelDef.Alias;\n                try\n                {\n                    modelDef.Alias = table;\n                    return fn();\n                }\n                finally\n                {\n                    modelDef.Alias = hold;\n                }\n            }\n        }\n\n        public static void DropAndCreateTable<T>(this IDbConnection db, string table)\n        {\n            ExecWithAlias<T>(table, () =>\n            {\n                db.DropAndCreateTable<T>();\n                return null;\n            });\n        }\n\n        public static long Insert<T>(this IDbConnection db, string table, T obj, bool selectIdentity = false)\n        {\n            return (long) ExecWithAlias<T>(table, () => db.Insert(obj, selectIdentity));\n        }\n\n        public static List<T> Select<T>(this IDbConnection db, string table,\n            Func<SqlExpression<T>, SqlExpression<T>> expression)\n        {\n            return (List<T>) ExecWithAlias<T>(table, () => db.Select<T>(expression));\n        }\n\n        public static int Update<T>(this IDbConnection db, string table, T item, Expression<Func<T, bool>> where)\n        {\n            return (int) ExecWithAlias<T>(table, () => db.Update(item, where));\n        }\n    }\n}"
  },
  {
    "path": "test/TestBase/ScenarioFor.cs",
    "content": "﻿using FluentAssertions;\nusing KellermanSoftware.CompareNetObjects;\nusing System;\nusing System.Linq;\nusing Domain;\n\nnamespace TestBase\n{\n    public class ScenarioFor<TAggregateRoot> where TAggregateRoot : IAggregateRoot\n    {\n        private TAggregateRoot _aggregateRoot;\n        private Action<TAggregateRoot>[] _whens;\n\n        public ScenarioFor(Func<TAggregateRoot> constructor) => _aggregateRoot = constructor();\n\n        public ScenarioFor<TAggregateRoot> When(params Action<TAggregateRoot>[] whens)\n        {\n            _whens = whens;\n            return this;\n        }\n\n        public ScenarioFor<TAggregateRoot> With(Action<TAggregateRoot> act)\n        {\n            act(_aggregateRoot);\n            return this;\n        }\n\n        public void Then(params object[] events)\n        {\n            var logic = new CompareLogic().Compare(_aggregateRoot.GetUncommittedChanges().ToArray(), events);\n            logic.AreEqual.Should().Be(true, \"Expected domain event(s) should be fired\");\n        }\n\n        public void ThenThrows<TException>(string message = \"\") where TException : Exception\n        {\n            Action act = () =>\n            {\n                foreach (var action in _whens)\n                {\n                    action(_aggregateRoot);\n                }\n            };\n\n            act.Should().Throw<TException>(message);\n        }\n    }\n}"
  },
  {
    "path": "test/TestBase/ScenarioForExisting.cs",
    "content": "﻿using System;\nusing System.Linq;\nusing Domain;\nusing FluentAssertions;\nusing KellermanSoftware.CompareNetObjects;\n\nnamespace TestBase\n{\n    public class ScenarioForExisting<TAggregateRoot> where TAggregateRoot : IAggregateRoot\n    {\n        private TAggregateRoot _aggregateRoot;\n        private Action<TAggregateRoot>[] _whens;\n\n        public ScenarioForExisting<TAggregateRoot> Given(Func<TAggregateRoot> aggregateRoot)\n        {\n            _aggregateRoot = aggregateRoot();\n            _aggregateRoot.MarkChangesAsCommitted();\n            return this;\n        }\n\n        public ScenarioForExisting<TAggregateRoot> When(params Action<TAggregateRoot>[] whens)\n        {\n            _whens = whens;\n            return this;\n        }\n\n        public ScenarioForExisting<TAggregateRoot> With(Action<TAggregateRoot> act)\n        {\n            act(_aggregateRoot);\n            return this;\n        }\n\n        public ScenarioForExisting<TAggregateRoot> Then(params object[] events)\n        {\n            foreach (var action in _whens)\n            {\n                action(_aggregateRoot);\n            }\n\n            var logic = new CompareLogic().Compare(_aggregateRoot.GetUncommittedChanges().ToArray(), events);\n            logic.AreEqual.Should().Be(true, \"Expected domain event(s) should be fired\");\n            return this;\n        }\n\n        public ScenarioForExisting<TAggregateRoot> AlsoAssert(Func<TAggregateRoot, bool> expression)\n        {\n            expression(_aggregateRoot).Should().Be(true, \"AlsoAssert is not validated maybe event is not applied\");\n            return this;\n        }\n\n        public void ThenNone()\n        {\n            foreach (var action in _whens)\n            {\n                action(_aggregateRoot);\n            }\n\n            _aggregateRoot.GetUncommittedChanges().ToArray().Should()\n                .BeEmpty(\"Aggregate should not have any events! But founded.\");\n        }\n\n        public void ThenThrows<TException>(string message = null) where TException : Exception\n        {\n            Action act = () =>\n            {\n                foreach (var action in _whens)\n                {\n                    action(_aggregateRoot);\n                }\n            };\n\n            if (message != null)\n                act.Should().Throw<TException>().WithMessage(message);\n            else\n                act.Should().Throw<TException>();\n        }\n    }\n}"
  },
  {
    "path": "test/TestBase/SpecBase.cs",
    "content": "﻿using System;\nusing System.Linq;\nusing AutoFixture;\nusing Domain;\n\nnamespace TestBase\n{\n    public abstract class SpecBase<TAggregate> : SpecBase where TAggregate : IAggregateRoot\n    {\n        protected virtual ScenarioForExisting<TAggregate> ScenarioForExisting()\n        {\n            return base.ScenarioForExisting<TAggregate>();\n        }\n        \n        protected ScenarioFor<TAggregate> ScenarioFor(Func<TAggregate> constructor)\n        {\n            return base.ScenarioFor<TAggregate>(constructor);\n        }\n    }\n\n    public abstract class SpecBase\n    {\n        protected virtual ScenarioForExisting<TAggregate> ScenarioForExisting<TAggregate>() where TAggregate : IAggregateRoot\n        {\n            return new ScenarioForExisting<TAggregate>();\n        }\n        \n        protected virtual ScenarioFor<TAggregate> ScenarioFor<TAggregate>(Func<TAggregate> constructor) where TAggregate : IAggregateRoot\n        {\n            return new ScenarioFor<TAggregate>(constructor);\n        }\n        \n        private static readonly Fixture fixture = new Fixture();\n\n        protected T Random<T>()\n        {\n            if (typeof(T) == typeof(long))\n            {\n                return (T) Convert.ChangeType(new Random().Next(),\n                    typeof(T)); // workaround to avoid autoFixture's similer long values \n            }\n\n            return fixture.Create<Generator<T>>().First();\n        }\n    }\n}\n"
  },
  {
    "path": "test/TestBase/TestBase.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n\n    <PropertyGroup>\n        <TargetFramework>netcoreapp3.0</TargetFramework>\n\n        <IsPackable>false</IsPackable>\n    </PropertyGroup>\n\n    <ItemGroup>\n        <PackageReference Include=\"AutoFixture\" Version=\"4.11.0\" />\n        <PackageReference Include=\"CompareNETObjects\" Version=\"4.63.0\" />\n        <PackageReference Include=\"FakeItEasy\" Version=\"5.2.0\" />\n        <PackageReference Include=\"FluentAssertions\" Version=\"5.9.0\" />\n        <PackageReference Include=\"FluentValidation.AspNetCore\" Version=\"8.5.0\" />\n        <PackageReference Include=\"Microsoft.Extensions.Configuration.Json\" Version=\"3.0.0\" />\n        <PackageReference Include=\"Microsoft.Extensions.DependencyInjection\" Version=\"3.0.0\" />\n        <PackageReference Include=\"Microsoft.NET.Test.Sdk\" Version=\"16.3.0\" />\n        <PackageReference Include=\"ServiceStack.OrmLite.Sqlite\" Version=\"5.7.0\" />\n        <PackageReference Include=\"xunit\" Version=\"2.4.1\" />\n        <PackageReference Include=\"xunit.runner.visualstudio\" Version=\"2.4.1\" />\n    </ItemGroup>\n\n    <ItemGroup>\n      <ProjectReference Include=\"..\\..\\src\\Domain\\Domain.csproj\" />\n    </ItemGroup>\n\n</Project>\n"
  },
  {
    "path": "test/TestBase/TestBaseWithInMemoryDb.cs",
    "content": "using Xunit;\n\nnamespace TestBase\n{\n    public abstract class TestBaseWithInMemoryDb : TestBaseWithIoC, IClassFixture<InMemoryDatabaseFixture>\n    {\n        protected static InMemoryDatabaseFixture InMemoryDb { get; private set; }\n        \n\n        protected TestBaseWithInMemoryDb(InMemoryDatabaseFixture inMemoryDatabaseFixture)\n        {\n            InMemoryDb = inMemoryDatabaseFixture;\n        }\n\n        public override void Dispose()\n        {\n            base.Dispose();\n            InMemoryDb.Dispose();\n        }\n    }\n}"
  },
  {
    "path": "test/TestBase/TestBaseWithIoC.cs",
    "content": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Linq.Expressions;\nusing AutoFixture;\nusing FakeItEasy;\nusing Microsoft.Extensions.Configuration;\nusing Microsoft.Extensions.DependencyInjection;\n\nnamespace TestBase\n{\n    public abstract class TestBaseWithIoC : IDisposable\n    {\n        private IServiceProvider _localResolver;\n        private readonly IServiceCollection _services;\n\n        protected TestBaseWithIoC() => _services = new ServiceCollection();\n\n        protected IConfiguration Configuration => InMemoryConfiguration != null\n            ? new ConfigurationBuilder().AddInMemoryCollection(InMemoryConfiguration).Build()\n            : new ConfigurationBuilder().AddJsonFile(ConfigJsonFilename).Build();\n\n        protected virtual IDictionary<string, string> InMemoryConfiguration => null;\n\n        protected virtual string ConfigJsonFilename => \"appsettings.test.json\";\n\n        public virtual void Dispose()\n        {\n        }\n\n        protected TestBaseWithIoC ConfigureServices(Action<IServiceCollection> builder)\n        {\n            builder(_services);\n            return this;\n        }\n\n        public void Build()\n        {\n            _localResolver = _services.BuildServiceProvider();\n        }\n\n        protected T GetRequiredService<T>() => _localResolver.GetRequiredService<T>();\n\n        protected virtual T Fake<T>(bool strict = false) where T : class\n        {\n            return A.Fake<T>(cfg =>\n            {\n                if (strict)\n                {\n                    cfg.Strict();\n                }\n            });\n        }\n\n        protected virtual T FakeAndRegister<T>(bool strict = false)\n            where T : class\n        {\n            T a = Fake<T>();\n\n            _services.AddSingleton(c => a);\n\n            return a;\n        }\n\n        protected virtual T FakeAndRegisterWithType<T>(bool strict = false)\n            where T : class\n        {\n            T a = Fake<T>();\n\n            _services.AddSingleton(typeof(T), c => a);\n\n            return a;\n        }\n\n        protected virtual void Verify(Expression<Action> callSpecification, int numberOfTimes = 1)\n        {\n            A.CallTo(callSpecification).MustHaveHappened(numberOfTimes, Times.Exactly);\n        }\n\n        protected virtual void Stub<T>(Expression<Func<T>> callSpecification, T stubbingValue)\n        {\n            A.CallTo(callSpecification).Returns(stubbingValue);\n        }\n\n        protected virtual T Ignore<T>() => A<T>.Ignored;\n\n        protected T Matches<T>(Expression<Func<T, bool>> predicate) => A<T>.That.Matches(predicate);\n\n        private static readonly Fixture fixture = new Fixture();\n\n        protected T Random<T>()\n        {\n            if (typeof(T) == typeof(long))\n            {\n                return (T) Convert.ChangeType(new Random().Next(),\n                    typeof(T)); // workaround to avoid autoFixture's similer long values \n            }\n\n            return fixture.Create<Generator<T>>().First();\n        }\n    }\n}"
  }
]