Skip to content

Commit

Permalink
Add AutoMapper extension (#84)
Browse files Browse the repository at this point in the history
---------

Co-authored-by: mostafa fbh <mostafafbh@yahoo.com>
  • Loading branch information
Reza-Noei and mostafa fbh authored Jun 29, 2024
1 parent 6ba4587 commit 0a93a4e
Show file tree
Hide file tree
Showing 11 changed files with 384 additions and 5 deletions.
18 changes: 16 additions & 2 deletions BSN.Commons.sln
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,13 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BSN.Commons.Orm.EntityFrame
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BSN.Commons.Users", "Source\BSN.Commons.Users\BSN.Commons.Users.csproj", "{213ABCEF-7E9A-4CE5-A3EF-289C9781344D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BSN.Commons.Orm.Redis", "Source\BSN.Commons.Orm.Redis\BSN.Commons.Orm.Redis.csproj", "{1A1586E8-46EB-43AC-91EC-F6EDCA5689A9}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BSN.Commons.Orm.Redis", "Source\BSN.Commons.Orm.Redis\BSN.Commons.Orm.Redis.csproj", "{1A1586E8-46EB-43AC-91EC-F6EDCA5689A9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BSN.Commons.Orm.Redis.Tests", "Test\BSN.Commons.Orm.Redis.Tests\BSN.Commons.Orm.Redis.Tests.csproj", "{2D1DB295-5181-48D7-8EC0-1147ED2DAD4A}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BSN.Commons.Orm.Redis.Tests", "Test\BSN.Commons.Orm.Redis.Tests\BSN.Commons.Orm.Redis.Tests.csproj", "{2D1DB295-5181-48D7-8EC0-1147ED2DAD4A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BSN.Commons.AutoMapper", "Source\BSN.Commons.AutoMapper\BSN.Commons.AutoMapper.csproj", "{279E7016-E2E9-430E-82A3-C9037FE0E08E}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BSN.Commons.AutoMapper.Tests", "Test\BSN.Commons.AutoMapper.Tests\BSN.Commons.AutoMapper.Tests.csproj", "{E8077467-8559-4669-B9FA-22530F1411E1}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Expand Down Expand Up @@ -93,6 +97,14 @@ Global
{2D1DB295-5181-48D7-8EC0-1147ED2DAD4A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2D1DB295-5181-48D7-8EC0-1147ED2DAD4A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2D1DB295-5181-48D7-8EC0-1147ED2DAD4A}.Release|Any CPU.Build.0 = Release|Any CPU
{279E7016-E2E9-430E-82A3-C9037FE0E08E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{279E7016-E2E9-430E-82A3-C9037FE0E08E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{279E7016-E2E9-430E-82A3-C9037FE0E08E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{279E7016-E2E9-430E-82A3-C9037FE0E08E}.Release|Any CPU.Build.0 = Release|Any CPU
{E8077467-8559-4669-B9FA-22530F1411E1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E8077467-8559-4669-B9FA-22530F1411E1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E8077467-8559-4669-B9FA-22530F1411E1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E8077467-8559-4669-B9FA-22530F1411E1}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -108,6 +120,8 @@ Global
{213ABCEF-7E9A-4CE5-A3EF-289C9781344D} = {DC377ADC-CC9D-4785-81BE-726DBF5F3096}
{1A1586E8-46EB-43AC-91EC-F6EDCA5689A9} = {DC377ADC-CC9D-4785-81BE-726DBF5F3096}
{2D1DB295-5181-48D7-8EC0-1147ED2DAD4A} = {5C6BA7B5-832A-495A-AF5E-C2A74F6A1EF9}
{279E7016-E2E9-430E-82A3-C9037FE0E08E} = {DC377ADC-CC9D-4785-81BE-726DBF5F3096}
{E8077467-8559-4669-B9FA-22530F1411E1} = {5C6BA7B5-832A-495A-AF5E-C2A74F6A1EF9}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {BCAF76D3-AA3C-4D0F-8D10-34065F8FED09}
Expand Down
8 changes: 5 additions & 3 deletions Build/build.cake
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,11 @@ var projects = new List<(string path, string name, string version)>
{
("BSN.Commons/", "BSN.Commons.csproj", solutionVersion),
("BSN.Commons.Users/", "BSN.Commons.Users.csproj", solutionVersion),
("BSN.Commons.PresentationInfrastructure/", "BSN.Commons.PresentationInfrastructure.csproj", solutionVersion),
("BSN.Commons.Orm.Redis/", "BSN.Commons.Orm.Redis.csproj", solutionVersion),
("BSN.Commons.AutoMapper/", "BSN.Commons.AutoMapper.csproj", solutionVersion),
("BSN.Commons.Orm.EntityFramework/", "BSN.Commons.Orm.EntityFramework.csproj", solutionVersion),
("BSN.Commons.Orm.EntityFrameworkCore/", "BSN.Commons.Orm.EntityFrameworkCore.csproj", solutionVersion),
("BSN.Commons.Orm.Redis/", "BSN.Commons.Orm.Redis.csproj", solutionVersion)
("BSN.Commons.PresentationInfrastructure/", "BSN.Commons.PresentationInfrastructure.csproj", solutionVersion)
};

var mainProject = "../Source/BSN.Commons/BSN.Commons.csproj";
Expand All @@ -35,7 +36,8 @@ var testProjects = new List<(string path, string name, string dll)>
("BSN.Commons.Tests/", "BSN.Commons.Tests.csproj", "bin/Release/net472/BSN.Commons.Tests.dll"),
("BSN.Commons.Orm.EntityFramework.Tests/", "BSN.Commons.Orm.EntityFramework.Tests.csproj", "bin/Release/net48/BSN.Commons.Orm.EntityFramework.Tests.dll"),
("BSN.Commons.Orm.EntityFrameworkCore.Tests/", "BSN.Commons.Orm.EntityFrameworkCore.Tests.csproj", "bin/Release/netcoreapp3.1/BSN.Commons.Orm.EntityFrameworkCore.Tests.dll"),
("BSN.Commons.Orm.Redis.Tests/", "BSN.Commons.Orm.Redis.Tests.csproj", "bin/Release/net8.0/BSN.Commons.Orm.Redis.Tests.dll")
("BSN.Commons.Orm.Redis.Tests/", "BSN.Commons.Orm.Redis.Tests.csproj", "bin/Release/net8.0/BSN.Commons.Orm.Redis.Tests.dll"),
("BSN.Commons.AutoMapper.Tests/", "BSN.Commons.AutoMapper.Tests.csproj", "bin/Release/net8.0/BSN.Commons.AutoMapper.Tests.dll")
};
var coverageResultsFileName = "coverage.xml";
var testResultsFileName = "nunitResults.xml";
Expand Down
47 changes: 47 additions & 0 deletions Source/BSN.Commons.AutoMapper/BSN.Commons.AutoMapper.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>net8.0</TargetFrameworks>
<AssemblyVersion>1.15.0</AssemblyVersion>
<FileVersion>1.15.0</FileVersion>
<Authors>BSN Developers</Authors>
<Company>BSN Company</Company>
<Description>AutoMapper Helpers for using AutoMapper in enterprise application.</Description>
<Copyright>BSN Co 2019-2024</Copyright>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<PackageProjectUrl>https://github.com/BSVN/Commons</PackageProjectUrl>
<RepositoryUrl>https://github.com/BSVN/Commons.git</RepositoryUrl>
<RepositoryType>git</RepositoryType>
<PackageReleaseNotes>Please see CHANGELOG.md</PackageReleaseNotes>
<Version>1.15.0</Version>
<ProduceReferenceAssembly>True</ProduceReferenceAssembly>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
<Title>BSN.Commons.AutoMapper</Title>
<PackageReadmeFile>README.md</PackageReadmeFile>
<IncludeSymbols>True</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<PackageIcon>BSN.jpg</PackageIcon>
<PackageTags>BSN;Commons;AutoMapper</PackageTags>
<!-- Optional: Publish the repository URL in the built .nupkg (in the NuSpec <Repository> element) -->
<PublishRepositoryUrl>true</PublishRepositoryUrl>
<!-- Optional: Embed source files that are not tracked by the source control manager in the PDB -->
<EmbedUntrackedSources>true</EmbedUntrackedSources>
</PropertyGroup>

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="AutoMapper" Version="13.0.1" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\BSN.Commons.PresentationInfrastructure\BSN.Commons.PresentationInfrastructure.csproj" />
<ProjectReference Include="..\BSN.Commons\BSN.Commons.csproj" />
</ItemGroup>

</Project>
20 changes: 20 additions & 0 deletions Source/BSN.Commons.AutoMapper/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Changelog

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [1.15.0] - 2024-06-29
Fixed issue with mapping between domain and view models.

### Added
- README.md and CHANGELOG.md
- Added support for AutoMapper 13.0.1
- Added predefined conversions for mapping `BSN.Commons.PresentationInfrastructure` Models.

### Fixed
- Resolve some missing elements in nupkg.

### Changed
- Update documentation.
40 changes: 40 additions & 0 deletions Source/BSN.Commons.AutoMapper/CommonsMappingProfile.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
using AutoMapper;
using BSN.Commons.Responses;

namespace BSN.Commons.AutoMapper
{
public class CommonMapperProfile : Profile
{
public CommonMapperProfile()
{
CreateMap(typeof(PagedEntityCollection<>), typeof(PaginationMetadata)).ConvertUsing(typeof(PagedEntityCollectionToMetaDataConverter<>));

CreateMap(typeof(IEnumerable<>), typeof(CollectionViewModel<>)).ConvertUsing(typeof(GenericIEnumerableToCollectionViewModelConverter<,>));
}

private class PagedEntityCollectionToMetaDataConverter<TDomain> : ITypeConverter<PagedEntityCollection<TDomain>, PaginationMetadata>
{
public PaginationMetadata Convert(PagedEntityCollection<TDomain> source, PaginationMetadata destination, ResolutionContext context)
{
return new PaginationMetadata()
{
Page = source.CurrentPage,
PageCount = source.PageSize,
PageSize = source.PageSize,
RecordCount = source.RecordCount
};
}
}

private class GenericIEnumerableToCollectionViewModelConverter<TDomain, TViewModel> : ITypeConverter<IEnumerable<TDomain>, CollectionViewModel<TViewModel>>
{
public CollectionViewModel<TViewModel> Convert(IEnumerable<TDomain> source, CollectionViewModel<TViewModel> destination, ResolutionContext context)
{
return new CollectionViewModel<TViewModel>
{
Items = context.Mapper.Map<IEnumerable<TViewModel>>(source)
};
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using AutoMapper;
using Microsoft.Extensions.DependencyInjection;

namespace BSN.Commons.AutoMapper.Extensions
{
public static class IServiceCollectionExtensions
{
public static IServiceCollection AddAutoMapper(this IServiceCollection services, Action<IMapperConfigurationExpression> configure)
{
var mappingConfig = new MapperConfiguration(config =>
{
MapperConfigurationExpression mapperConfigurationExpression = new MapperConfigurationExpression();
configure(mapperConfigurationExpression);

configure(config);

config.AddProfile(new CommonMapperProfile());
});

IMapper mapper = mappingConfig.CreateMapper();

services.AddSingleton(mapper);

return services;
}
}
}
59 changes: 59 additions & 0 deletions Source/BSN.Commons.AutoMapper/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# BSN.Commons.AutoMapper

This package contains some facilities for using AutoMapper in Enterprise Applications.

AutoMapper is a popular library for mapping objects from one Model to Another. It simplifies the process of mapping complex objects and reduces the amount of code needed to perform these mappings stuffs.

**BSN.Commons.Automapper** is a package that provides some predefined mappings for **BSN.Commons.PresentationInfrastructure** Models.
This helps **BSN.Commons** users to skip writing required mapping to dealing with these Models.

### 1. Installation
To use this package, you need to first install it on your web api or presentation layer. You can do this by running the following command (in package manager console):
```
Install-Package BSN.Commons.AutoMapper
```

### 2. Add Your required mapping profiles
To use these predefined mapping profiles and injecting your preferred profiles you just need to add following line in the `ServiceCollection`:
```
services.AddAutoMapper(config => config.AddProfile<YourMappingProfile>());
```
or
```
services.AddAutoMapper(config =>
{
config.AddProfile<YourFirstMappingProfile>();
config.AddProfile<YourSecondMappingProfile>();
});
```

### 3. Predefined mapping profile:

Provided built in mapping profile contains following mappings:

#### PagedEntityCollectionToMetaDataConverter:
A default converter which converts `PagedEntityCollection<TDomain>` to `PaginationMetadata`.
#### GenericIEnumerableToCollectionViewModelConverter:
A generic default converter which converts `IEnumerable<TDomain>` to `CollectionViewModel<TViewModel>`

### 4. Example Usage

#### PagedEntityCollectionToMetaDataConverter
```
var pagedEntities = new PagedEntityCollection<Product>(products, 1, 10, 100);
var paginationMetadata = mapper.Map<PaginationMetadata>(pagedEntities);
```

#### GenericIEnumerableToCollectionViewModelConverter
```
var products = new List<Product>
{
new Product { Id = 1, Name = "Product 1" },
new Product { Id = 2, Name = "Product 2" },
new Product { Id = 3, Name = "Product 3" }
};
var collectionViewModel = mapper.Map<CollectionViewModel<ProductViewModel>>(products);
```

`BSN.Commons.AutoMapper` is Copyright © 2024 BSN and other contributors under the BSN license.
19 changes: 19 additions & 0 deletions Test/BSN.Commons.AutoMapper.Tests/AutoMapperTestBase.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using AutoMapper;

namespace BSN.Commons.AutoMapper.Tests
{
public abstract class AutoMapperTestBase
{
protected readonly IMapper _mapper;

protected AutoMapperTestBase()
{
var configuration = new MapperConfiguration(cfg =>
{
cfg.AddProfile<CommonMapperProfile>();
});

_mapper = configuration.CreateMapper();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="AutoMapper" Version="13.0.1" />
<PackageReference Include="coverlet.collector" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="Moq" Version="4.20.70" />
<PackageReference Include="NUnit" Version="3.14.0" />
<PackageReference Include="NUnit.Analyzers" Version="3.9.0" />
<PackageReference Include="NUnit3TestAdapter" Version="4.5.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\Source\BSN.Commons.AutoMapper\BSN.Commons.AutoMapper.csproj" />
<ProjectReference Include="..\..\Source\BSN.Commons.PresentationInfrastructure\BSN.Commons.PresentationInfrastructure.csproj" />
<ProjectReference Include="..\..\Source\BSN.Commons\BSN.Commons.csproj" />
</ItemGroup>

<ItemGroup>
<Using Include="NUnit.Framework" />
</ItemGroup>

</Project>
Loading

0 comments on commit 0a93a4e

Please sign in to comment.