如何在webapi项目中使用Unity实现Automaper(IMappingEngine)的ioc

时间:2016-07-01 15:08:33

标签: c#-4.0 asp.net-web-api unity-container automapper

我正在开发webapi项目并广泛使用Automapper来映射对象。 目前我正在使用Mapper.Map

任何人都可以指导我如何实现这个目标吗?如何在Unity中注册IMappingEngine时调用此configure方法?

我当前的自动播放器映射:

public static class AutomapperConfiguration
{
    public static void Configure()
    {
        Mapper.Initialize(cfg =>
        {
            cfg.ConstructServicesUsing(type => UnityConfig.GetConfiguredContainer().Resolve(type));

            cfg.CreateMap<Logger, Log>()
                  .ForMember(d => d.TxId, opt => opt.ResolveUsing<AsRunTxIdValueResolver>());
        }
    }
}

由于

1 个答案:

答案 0 :(得分:1)

您可以使用automapper配置文件创建各种映射器并注册所有配置文件,如下所示:

public static class AutomapperConfiguration
{
    public static MapperConfiguration MyMapperConfiguration;
    public static void Configure()
    {
        MyMapperConfiguration = new MapperConfiguration(cfg =>
        {
            var types = typeof(Program).Assembly.GetTypes();
            var profiles = types.Where(x => x.IsSubclassOf(typeof(Profile)))
                                .Select(Activator.CreateInstance)
                                .OfType<Profile>()
                                .ToList();
            profiles.Each(p => cfg.AddProfile(p));
        });

        MapperConfiguration.AssertConfigurationIsValid();       
    }
}

您的automapper个人资料类将如下所示:

public class LoggerProfile : Profile
{
    protected override void Configure()
    {
        CreateMap<Logger,Log>()
          .ForMember(d => d.TxId, opt => opt.ResolveUsing<AsRunTxIdValueResolver>());
    }
}

在你的startup.cs中,你必须注册这样的映射器:

AutoMapperConfiguration.RegisterMappers();