2

我已经使用 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>());

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

有任何想法吗?谢谢

4

2 回答 2

1

好吧,我找到了一种方法,方法是使用AddProfile. 有一个采用配置文件实例的重载,因此我可以在将实例传递给AddProfile方法之前解析它。

于 2010-03-08T19:02:32.013 回答
0

我的一位客户想知道与DownChapel相同的事情,他的回答促使我编写了一些示例应用程序。

我所做的是以下。首先从组件中检索所有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上找到,但大部分重要代码都在这里共享。

于 2017-10-24T06:28:34.807 回答