X

Automapper: Mapping Objects Part 7 of 7 (Startup Registration)

automapper

In this last part of the series I wanted to talk about how to register automapper at startup of your web application, in doing so it would help speed things up with automapper.

There are many ways to do it, the easiest way is to just have a method inside Global.asax.cs file in your Application_Start like below

 protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
            RegisterAutoMapper();                       
        }

        private static void RegisterAutoMapper()
        {
            Mapper.CreateMap()
             .ForMember(dest => dest.PurchaseHour, opt => opt.MapFrom(src => src.PurchaseDate.Hour))
             .ForMember(dest => dest.PurchaseMinute, opt => opt.MapFrom(src => src.PurchaseDate.Minute));

          //rest of the mapping
        }

And if you are using an IoC container, than one can use the Command Pattern for a StartupTask, below is an example of using ServiceLocator for startup.

 protected void Application_Start()
 {
      Startup.Run();            
 }

public class Startup 
{
     public static void Run()
     {
            var startupTask = ServiceLocator.Current.GetAllInstances();

            foreach (var task in startupTask)
            {
                task.Execute();
            }
        }
}

public interface IStartupTask
{
        void Execute();
}

 public class AutoMapperStartupTask: IStartupTask
 {      
        public void Execute()
        {
              Mapper.CreateMap()
             .ForMember(dest => dest.PurchaseHour, opt => opt.MapFrom(src => src.PurchaseDate.Hour))
             .ForMember(dest => dest.PurchaseMinute, opt => opt.MapFrom(src => src.PurchaseDate.Minute));
            //rest of mapping code
         }
}

Note: one will need to remove all the CreateMap code in their controller to here, you do not need to call CreateMap anymore since the startup task takes care of it.

This concludes our final segment on Automapper, hopefully you will find this helpful 😛

Previous Post:
Part 1 (NullSubsitution)
Part 2 (Flattening by Convention)
Part 3 (Nested Mapping)
Part 4 (Projection)
Part 5 (CustomResolver)
Part 6 (CustomFormatter)

Categories: .NET Automapper
Taswar Bhatti:

View Comments (2)

Related Post