How to Configure AutoMapper Once Per AppDomain

后端 未结 4 971
别跟我提以往
别跟我提以往 2020-12-24 07:36

My current project with assemblies for the domain model, MVC web application, and unit tests. How can I set up the AutoMapper configuration so that all assemblies reference

4条回答
  •  囚心锁ツ
    2020-12-24 08:26

    I have been moving my AutoMapper CreateMap calls into classes that live beside my view models. They implement an IAutomapperRegistrar interface. I use reflection to find the IAutoMapperRegistrar implementations, create an instance and add the registrations.

    Here is the interface:

    public interface IAutoMapperRegistrar
    {
        void RegisterMaps();
    }
    

    Here is an implementation of the interface:

    public class EventLogRowMaps : IAutoMapperRegistrar
    {
        public void RegisterMaps()
        {
            Mapper.CreateMap()
                .ConstructUsing(he => new EventLogRow(he.Id))
                .ForMember(m => m.EventName, o => o.MapFrom(e => e.Description))
                .ForMember(m => m.UserName, o => o.MapFrom(e => e.ExecutedBy.Username))
                .ForMember(m => m.DateExecuted, o => o.MapFrom(e => string.Format("{0}", e.DateExecuted.ToShortDateString())));
        }
    }
    

    Here is the code that performs the registrations in my Application_Start:

    foreach (Type foundType in Assembly.GetAssembly(typeof(ISaveableModel)).GetTypes())
    {
        if(foundType.GetInterfaces().Any(i => i == typeof(IAutoMapperRegistrar)))
        {
            var constructor = foundType.GetConstructor(Type.EmptyTypes);
            if (constructor == null) throw new ArgumentException("We assume all IAutoMapperRegistrar classes have empty constructors.");
            ((IAutoMapperRegistrar)constructor.Invoke(null)).RegisterMaps();
        }
    }
    

    I figure it's appropriate and at least a bit logical; they are a lot easier to follow that way. Before I had hundreds of registrations in one huge bootstrap method and that was starting to become a pain in the ass.

    Thoughts?

提交回复
热议问题