Pet*_*ron 7 automapper asp.net-mvc-3
在我的ASP.NET MVC应用程序中,我应该定义AutoMapper映射吗?
Mapper.CreateMap<User, UserViewModel>();
Run Code Online (Sandbox Code Playgroud)
目前我在BaseController的构造函数中定义了这些,我的所有Controlllers都是从这个构造函数派生出来的.这是最好的地方吗?
我认为回答这个问题有点迟,但也许有人可以使用我的答案.
我使用Ninject来解析依赖关系,所以我为AutoMapper创建了Ninject模块.这是代码:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
正如您在加载时看到的那样,它扫描程序集以实现IViewModelMapping,然后运行Create方法.
这是IViewModelMapping的代码:
interface IViewModelMapping
{
void Create(IConfiguration configuration);
}
Run Code Online (Sandbox Code Playgroud)
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());
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2408 次 |
| 最近记录: |