【问题标题】:How to implement ioc for Automapper (IMappingEngine) using Unity in webapi project如何在 webapi 项目中使用 Unity 为 Automapper (IMappingEngine) 实现 ioc
【发布时间】:2016-07-01 15:08:32
【问题描述】:

我正在开发 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>());
        }
    }
}

谢谢

【问题讨论】:

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


    【解决方案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();       
        }
    }
    

    您的自动映射器配置文件类将如下所示:

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

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

    AutoMapperConfiguration.RegisterMappers();
    

    【讨论】:

    • 如何像依赖注入一样使用它?曾经有一个IMappingEngine
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多