MVC 3: AutoMapper and project / solution structure

I just started using AutoMapper in my MVC 3 project, and I wonder how people here structure their projects when using it. I created a MapManager that simply has the SetupMaps method, which I call in global.asax to create the original map configurations. I also need to use ValueResolver for one of my mappings. For me, this particular ValueResolver will be needed in several different places and will simply return the value from Article.GenerateSlug .

So my questions are:

  • How do you control the initial creation of all your maps ( Mapper.CreateMap )?
  • Where do you put the classes for your ValueResolver in your project? Are you creating subfolders in the Model folder or something else?

Thanks for any help.

+4
source share
1 answer

I will not speak with question 2 as his personal preference, but for 1 I usually use one or more AutoMapper.Profile to store all of my Mapper.CreateMap for a specific purpose (domaintoviewmodel, etc.).

 public class ViewModelToDomainAutomapperProfile : Profile { public override string ProfileName { get { return "ViewModelToDomain"; } } protected override void Configure() { CreateMap<TripRegistrationViewModel, TripRegistration>() .ForMember(x=>x.PingAttempts, y => y.Ignore()) .ForMember(x=>x.PingResponses, y => y.Ignore()); } } 

then I create a loader ( IInitializer ) that configures Mapper, adding all my profiles.

 public class AutoMapperInitializer : IInitializer { public void Execute() { Mapper.Initialize(x => { x.AddProfile<DomainToViewModelAutomapperProfile>(); x.AddProfile<ViewModelToDomainAutomapperProfile>(); }); } } 

then in my global.asax I get all the instances of IInitializer and IInitializer them through Execute() .

 foreach (var initializer in ObjectFactory.GetAllInstances<IInitializer>()) { initializer.Execute(); } 

what is my overall strategy.


upon request, here is the implementation of the implementation of the last step.

 var iInitializer = typeof(IInitializer); List<IInitializer> initializers = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(s => s.GetTypes()) .Where(p => iInitializer.IsAssignableFrom(p) && p.IsClass) .Select(x => (IInitializer) Activator.CreateInstance(x)).ToList(); foreach (var initializer in initializers) { initializer.Execute(); } 
+3
source

All Articles