【发布时间】:2011-11-13 23:08:07
【问题描述】:
如何避免需要这样的代码:
public static class BusinessLogicAutomapper
{
public static bool _configured;
public static void Configure()
{
if (_configured)
return;
Mapper.CreateMap<Post, PostModel>();
_configured = true;
}
}
在我的 BL 程序集中,并且必须在我的 MVC 应用程序中从我的 Global.asax 调用 Configure()?
我的意思是,我期待这样的电话:
public PostModel GetPostById(long id)
{
EntityDataModelContext context = DataContext.GetDataContext();
Post post = context.Posts.FirstOrDefault(p => p.PostId == id);
PostModel mapped = Mapper.Map<Post, PostModel>(post);
return mapped;
}
到Mapper.Map<TIn,TOut> 来生成映射器(如果它不存在),而不必自己手动创建它(我什至不应该知道这个内部工作)。如何以声明方式为 AutoMapper 创建映射器?
需要一个对 AutoMapper 来说很自然的解决方案,但为了避免这种初始化而进行的扩展或一些架构更改也会起作用。
我正在使用 MVC 3、.NET 4,并且没有 IoC/DI(至少还没有)
【问题讨论】:
-
如果您没有 CreateMap 配置调用,当 Post -> PostModel 地图中的某些内容未对齐时会发生什么?也就是说,你在 Post 上重命名了某个东西,但在 PostModel 上没有重命名?
标签: c# automapper