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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); RegisterAutoMapper(); } private static void RegisterAutoMapper() { Mapper.CreateMap<Order, OrderDateDto>() .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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
protected void Application_Start() { Startup.Run(); } public class Startup { public static void Run() { var startupTask = ServiceLocator.Current.GetAllInstances<IStartupTask>(); foreach (var task in startupTask) { task.Execute(); } } } public interface IStartupTask { void Execute(); } public class AutoMapperStartupTask: IStartupTask { public void Execute() { Mapper.CreateMap<Order, OrderDateDto>() .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 } } |
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)
[…] with automapper. There are many ways to do it, the easiest way is to just have a method inside… [full post] taswar Taswar Bhatti Blog .netautomapper 0 0 0 0 0 […]
could you give out the source code for these posts?
Unfortunately the code was on a laptop that I reformatted so I no longer have the code anymore 🙁
All there is on these post.