2011-04-25 154 views
7

在我的ASP.NET MVC應用程序中應該如何定義我的AutoMapper映射?何處定義AutoMapper映射?

Mapper.CreateMap<User, UserViewModel>(); 

目前我正在定義這些在BaseController的構造函數中,這是我的所有控制器派生自的。這是最好的地方嗎?

回答

9

我認爲這是有點晚來回答這個問題,但也許有人可以用我的答案。

我用Ninject來解決依賴關係,所以我創建Ninject模塊AutoMapper。下面是代碼:

public class AutoMapperModule : NinjectModule 
{ 
    public override void Load() 
    { 
     Bind<IConfiguration>().ToMethod(context => Mapper.Configuration); 
     Bind<IMappingEngine>().ToMethod(context => Mapper.Engine); 

     SetupMappings(Kernel.Get<IConfiguration>()); 

     Mapper.AssertConfigurationIsValid(); 
    } 

    private static void SetupMappings(IConfiguration configuration) 
    { 
     IEnumerable<IViewModelMapping> mappings = typeof(IViewModelMapping).Assembly 
      .GetExportedTypes() 
      .Where(x => !x.IsAbstract && 
         typeof(IViewModelMapping).IsAssignableFrom(x)) 
      .Select(Activator.CreateInstance) 
      .Cast<IViewModelMapping>(); 

     foreach (IViewModelMapping mapping in mappings) 
      mapping.Create(configuration); 
    } 
} 

正如你可以看到負載,它會掃描組件,用於IViewModelMapping的implementaion,然後運行創建方法。

這裏是IViewModelMapping的代碼:

interface IViewModelMapping 
{ 
    void Create(IConfiguration configuration); 
} 

典型實施IViewModelMapping的是這樣的:

public class RestaurantMap : IViewModelMapping 
{ 
    public void Create(IConfiguration configuration) 
    { 
     if (configuration == null) 
      throw new ArgumentNullException("configuration"); 

     IMappingExpression<RestaurantViewModel, Restaurant> map = 
      configuration.CreateMap<RestaurantViewModel, Restaurant>(); 
// some code to set up proper mapping 

     map.ForMember(x => x.Categories, o => o.Ignore()); 
    } 
} 
0

你引用的樣子AutoMapper的代碼,而不是StructureMap。

如果你使用靜態映射 方法,配置只需要 每個AppDomain發生一次。這意味着 把 配置代碼的最佳位置是在應用程序啓動 ,如Global.asax文件 ASP.NET應用程序。通常情況下, 配置引導程序類 是在自己的班級,這 引導程序類是從 啓動方法調用。

http://automapper.codeplex.com/wikipage?title=Getting%20Started&referringTitle=Home

+0

呃,我是個白癡。我的意思是AutoMapper。咳嗽藥太多。更新我的問題。 – 2011-04-25 12:46:08

1

this answer提到,AutoMapper現在已經推出了配置profiles組織您的映射配置。

因此,例如,你可以定義一個類來建立你的映射配置:

public class ProfileToOrganiseMappings : Profile 
{ 
    protected override void Configure() 
    { 
     Mapper.CreateMap<SourceModel, DestinationModel>(); 
     //other mappings could be defined here 
    } 
} 

再定義一個類來初始化的映射:

public static class AutoMapperWebConfiguration 
{ 
    public static void Configure() 
    { 
     Mapper.Initialize(cfg => 
     { 
      cfg.AddProfile(new ProfileToOrganiseMappings()); 
      //other profiles could be registered here 
     }); 
    } 
} 

然後最後,調用類在你的global.asax Application_Start()來配置這些映射:

protected void Application_Start() 
{ 
    ... 
    AutoMapperWebConfiguration.Configure(); 
}