Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to register AutoMapper 4.2.0 with Simple Injector

Updated to AutoMapper 4.2.0, and following the migration guide available here: https://github.com/AutoMapper/AutoMapper/wiki/Migrating-from-static-API/f4784dac61b91a0df130e252c91a0efd76ff51de#preserving-static-feel. Trying to translate code on that page for StructureMap to Simple Injector. Can someone show me what this code looks like in Simple Injector?

StructureMap

public class AutoMapperRegistry : Registry
{
    public AutoMapperRegistry()
    {
        var profiles =
            from t in typeof (AutoMapperRegistry).Assembly.GetTypes()
            where typeof (Profile).IsAssignableFrom(t)
            select (Profile)Activator.CreateInstance(t);

        var config = new MapperConfiguration(cfg =>
        {
            foreach (var profile in profiles)
            {
                cfg.AddProfile(profile);
            }
        });

        For<MapperConfiguration>().Use(config);
        For<IMapper>().Use(ctx => ctx.GetInstance<MapperConfiguration>().CreateMapper(ctx.GetInstance));
    }
}

Simple Injector

?
like image 302
James Avatar asked Feb 12 '16 19:02

James


2 Answers

Simple Injector's IPackage interface seems like the nearest equivalent of StructureMap's Registry type. Here's the package I use, building from @Steven's answer:

using System;
using System.Linq;
using System.Reflection;
//
using AutoMapper;
//
using SimpleInjector;
using SimpleInjector.Packaging;

public class AutoMapperPackage : IPackage
{
    public void RegisterServices(Container container)
    {
        var profiles = Assembly.GetExecutingAssembly()
            .GetTypes()
            .Where(x => typeof(AutoMapper.Profile).IsAssignableFrom(x));

        var config = new MapperConfiguration(cfg =>
        {
            foreach (var profile in profiles)
            {
                cfg.AddProfile(Activator.CreateInstance(profile) as AutoMapper.Profile);
            }
        });

        container.RegisterInstance<MapperConfiguration>(config);
        container.Register<IMapper>(() => config.CreateMapper(container.GetInstance));
    }
}

You would need to add the SimpleInjector.Packaging package, and then add a call to container.RegisterPackages(); in your bootstrap/configuration code.

Essentially, the only thing that really changes from StructureMap would be the last two lines.

like image 61
Tieson T. Avatar answered Sep 19 '22 23:09

Tieson T.


This would be the equivalent:

container.RegisterInstance<MapperConfiguration>(config);
container.Register<IMapper>(() => config.CreateMapper(container.GetInstance));
like image 39
Steven Avatar answered Sep 17 '22 23:09

Steven