Skip to content

Instantly share code, notes, and snippets.

@Tsabo
Last active July 23, 2016 03:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tsabo/995288b628781e9189d90b4f95dd95ac to your computer and use it in GitHub Desktop.
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
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