我一直在研究如何将 AutoMapper 注入到控制器中。我喜欢 Code Camp Server 的实现方式,它创建了一个围绕 AutoMapper 的 IMappingEngine 的包装器。依赖注入使用的是 StructureMap。但是,我需要在我的项目中使用 Castle Windsor。那么,我们如何使用 Windsor 实现以下依赖注入和设置呢?我并不寻求在 Castle Windsor 中逐行等效的实现。如果你想这样做,请随意。相反,Windsor 的 Registry 和 Profile 相当于 StructureMap 的什么?我需要 Profile 来定义像下面这样的 CreateMap<>。
谢谢。
会议控制器:
谢谢。
会议控制器:
public MeetingController(IMeetingMapper meetingMapper, ...)
会议映射工具:
public class MeetingMapper : IMeetingMapper
{
private readonly IMappingEngine _mappingEngine;
public MeetingMapper(IMappingEngine mappingEngine)
{
_mappingEngine = mappingEngine;
}
public MeetingInput Map(Meeting model)
{
return _mappingEngine.Map<Meeting, MeetingInput>(model);
}
......
}
自动映射注册表:
public class AutoMapperRegistry : Registry
{
public AutoMapperRegistry()
{
ForRequestedType<IMappingEngine>().TheDefault.Is.ConstructedBy(() => Mapper.Engine);
}
}
Meeting Mapper简介:
public class MeetingMapperProfile : Profile
{
public static Func<Type, object> CreateDependencyCallback = (type) => Activator.CreateInstance(type);
public T CreateDependency<T>()
{
return (T)CreateDependencyCallback(typeof(T));
}
protected override void Configure()
{
Mapper.CreateMap<MeetingInput, Meeting>().ConstructUsing(
input => CreateDependency<IMeetingRepository>().GetById(input.Id) ?? new Meeting())
.ForMember(x => x.UserGroup, o => o.MapFrom(x => x.UserGroupId))
.ForMember(x => x.Address, o => o.Ignore())
.ForMember(x => x.City, o => o.Ignore())
.ForMember(x => x.Region, o => o.Ignore())
.ForMember(x => x.PostalCode, o => o.Ignore())
.ForMember(x => x.ChangeAuditInfo, o => o.Ignore());
}
}