1

How do I register my AutoMapper class in SimpleInjector?

This is the part of my class where register Mapper SimpleInjector:

container.RegisterSingleton(Mapper.Configuration);
container.Register<IMapper>(**--What should I put here?--**)

This is my MapperConfig class:

public class AutoMapperConfig
{
    public static MapperConfiguration RegisterMappings()
    {
        return new MapperConfiguration(cfg =>
        {
            cfg.AddProfile(new DomainToViewModelMappingProfile());
            cfg.AddProfile(new ViewModelToDomainMappingProfile());
        });
    }
}
Dariel
  • 77
  • 1
  • 6
  • 1
    usually i call AutoMapperConfiguration.Configure(); in my GlobalAsax.cs on app_startup – federico scamuzzi Dec 30 '16 at 10:49
  • Possible duplicate of [How to register AutoMapper 4.2.0 with Simple Injector](http://stackoverflow.com/questions/35370733/how-to-register-automapper-4-2-0-with-simple-injector) – G0dsquad Dec 30 '16 at 10:49
  • Yes, as @federicoscamuzzi says, it's more typical to initialise AutoMapper in AppStart => `public static class AutomapperConfig { // static configuration class e.g. Mapper.Initialize(cfg => {...}) }` – G0dsquad Dec 30 '16 at 10:52
  • OK, but if I would not be using ASP.Net, if I would be using a Desktop application or Console – Dariel Dec 30 '16 at 11:35

1 Answers1

2

change your automapperConfig class to a static one .. like this:

public static class AutoMapperConfig
{
    public static MapperConfiguration RegisterMappings()
    {
        return new MapperConfiguration(cfg =>
        {
            cfg.AddProfile(new DomainToViewModelMappingProfile());
            cfg.AddProfile(new ViewModelToDomainMappingProfile());
        });
    }
}

then call it in your GlobalAsax.cs file in App_start like this:

 public class WebApiApplication : HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);


            // Register Mapping Configuration on Start up
            AutoMapperConfiguration.Configure();

        }

        protected void Application_End()
        {
            //Cleanup all resources

        }
    }
federico scamuzzi
  • 3,708
  • 1
  • 17
  • 24
  • OK, but if I would not be using ASP.Net, if I would be using a Desktop application or Console – Dariel Dec 30 '16 at 11:35
  • try to find the equivalent of App_start for your console or WPF application ..also maybe in your Program.cs at first line you can call AutoMapperConfiguration.Configure(); – federico scamuzzi Dec 30 '16 at 11:39