Last active
July 23, 2016 03:24
-
-
Save Tsabo/995288b628781e9189d90b4f95dd95ac to your computer and use it in GitHub Desktop.
Automatically register all Profiles's that can be located by using the ApplicationPartManager
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using AutoMapper; | |
using Microsoft.AspNetCore.Mvc.ApplicationParts; | |
// ReSharper disable once CheckNamespace | |
namespace Microsoft.Extensions.DependencyInjection | |
{ | |
/// <summary> | |
/// The auto mapper extensions. | |
/// </summary> | |
public static class AutoMapperExtensions | |
{ | |
// https://github.com/aspnet/Mvc/pull/4391/commits/f638c051fa79c293ea7a0a859ed9700db9a18d71 | |
/// <summary> | |
/// Automatically register all <see cref="Profile"/>'s that can be located by using the <see cref="ApplicationPartManager"/> | |
/// </summary> | |
/// <param name="services"></param> | |
public static void UseAutoMapper(this IServiceCollection services) | |
{ | |
services.AddSingleton(p => new MapperConfiguration(cfg => cfg.RegisterConfigurations(p.GetService<ApplicationPartManager>().ApplicationParts))); | |
services.AddSingleton(p => p.GetService<MapperConfiguration>().CreateMapper()); | |
} | |
private static void RegisterConfigurations(this IMapperConfigurationExpression config, IEnumerable<ApplicationPart> applicationParts) | |
{ | |
if (applicationParts == null) | |
throw new ArgumentNullException(nameof(applicationParts)); | |
applicationParts.OfType<AssemblyPart>() | |
.SelectMany(p => p.Types) | |
.Where(x => x.IsSubclassOf(typeof(Profile))) | |
.Where(x => x.GetConstructor(Type.EmptyTypes) != null) // Make sure it has a default parameterless constructor | |
.Select(Activator.CreateInstance) | |
.OfType<Profile>() | |
.ForEach(config.AddProfile); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment