在我的ASP.NET MVC应用程序中应该如何定义我的AutoMapper映射?何处定义AutoMapper映射?
Mapper.CreateMap<User, UserViewModel>();
目前我正在定义这些在BaseController的构造函数中,这是我的所有控制器派生自的。这是最好的地方吗?
在我的ASP.NET MVC应用程序中应该如何定义我的AutoMapper映射?何处定义AutoMapper映射?
Mapper.CreateMap<User, UserViewModel>();
目前我正在定义这些在BaseController的构造函数中,这是我的所有控制器派生自的。这是最好的地方吗?
我认为这是有点晚来回答这个问题,但也许有人可以用我的答案。
我用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());
}
}
你引用的样子AutoMapper的代码,而不是StructureMap。
如果你使用静态映射 方法,配置只需要 每个AppDomain发生一次。这意味着 把 配置代码的最佳位置是在应用程序启动 ,如Global.asax文件 ASP.NET应用程序。通常情况下, 配置引导程序类 是在自己的班级,这 引导程序类是从 启动方法调用。
http://automapper.codeplex.com/wikipage?title=Getting%20Started&referringTitle=Home
如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();
}
呃,我是个白痴。我的意思是AutoMapper。咳嗽药太多。更新我的问题。 – 2011-04-25 12:46:08