IoC with AutoMapper Profile使用Autofac

时间:2010-03-08 18:17:23

标签: automapper

我一直在使用AutoMapper一段时间了。我有一个类似的配置文件设置:

public class ViewModelAutoMapperConfiguration : Profile
    {
        protected override string ProfileName
        {
            get { return "ViewModel"; }
        }

        protected override void Configure()
        {
            AddFormatter<HtmlEncoderFormatter>();
            CreateMap<IUser, UserViewModel>();

        }
    }

我使用以下调用将其添加到映射器:

Mapper.Initialize(x => x.AddProfile<ViewModelAutoMapperConfiguration>());

但是,我现在想要使用IoC将依赖项传递给ViewModelAutoMapperConfiguration构造函数。我正在使用Autofac。我一直在阅读这篇文章:http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/05/11/automapper-and-ioc.aspx但我看不出这对配置文件有什么作用。

有什么想法吗? 感谢

2 个答案:

答案 0 :(得分:1)

好吧,我通过使用AddProfile的重载找到了一种方法。有一个带有配置文件实例的重载,所以我可以在将实例传递给AddProfile方法之前解析该实例。

答案 1 :(得分:0)

我的一位客户想知道DownChapel and his answer在编写一些示例应用程序时引发了我的想法。

我所做的是以下内容。 首先从组件中检索所有Profile类型,然后在IoC容器中注册它们(我使用的是Autofac)。

var loadedProfiles = RetrieveProfiles();
containerBuilder.RegisterTypes(loadedProfiles.ToArray());

在注册AutoMapper配置时,我正在解析所有Profile类型并从中解析实例。

private static void RegisterAutoMapper(IContainer container, IEnumerable<Type> loadedProfiles)
{
    AutoMapper.Mapper.Initialize(cfg =>
    {
        cfg.ConstructServicesUsing(container.Resolve);
        foreach (var profile in loadedProfiles)
        {
             var resolvedProfile = container.Resolve(profile) as Profile;
             cfg.AddProfile(resolvedProfile);
        }
    });
}

这样,您的IoC框架(Autofac)将解析Profile的所有依赖关系,因此它可以具有依赖关系。

public class MyProfile : Profile
{
    public MyProfile(IConvertor convertor)
    {
        CreateMap<Model, ViewModel>()
            .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Identifier))
            .ForMember(dest => dest.Name, opt => opt.MapFrom(src => convertor.Execute(src.SomeText)))
            ;
    }
}

完整的示例应用程序可以在GitHub找到,但大多数重要代码都是在这里共享的。

相关问题