开发者

MVC 3: AutoMapper and Project/Solution Structure

I've just started to use AutoMapper in my MVC 3 project and I'm wondering how people here structure their projects when using it. I've created a MapMan开发者_运维技巧ager which simply has a SetupMaps method that I call in global.asax to create the initial map configurations. I also need to use a ValueResolver for one of my mappings. For me, this particular ValueResolver will be needed in a couple of different places and will simply return a value from Article.GenerateSlug.

So my questions are:

  1. How do you manage the initial creation of all of your maps (Mapper.CreateMap)?
  2. Where do you put the classes for your ValueResolvers in your project? Do you create subfolders under your Model folder or something else entirely?

Thanks for any help.


i won't speak to question 2 as its really personal preference, but for 1 i generally use one or more AutoMapper.Profile to hold all 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 bootstrapper (IInitializer) that configures the Mapper, adding all of 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 instances of IInitializer and loop through them running Execute().

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

that's my general strategy.


by request, here is the reflection implementation of the final 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();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜