2010-03-08 115 views
2

我一直在使用AutoMapper一段时间。我有一个配置文件设置,如下所示:使用Autofac的AutoMapper配置文件IoC

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构造。我正在使用Autofac。我一直在阅读这篇文章:http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/05/11/automapper-and-ioc.aspx,但我不明白这将如何与配置文件一起工作。

任何想法? 谢谢

回答

1

那么,我发现了一种使用AddProfile超载的方法。有一个过载需要配置文件的实例,所以我可以在将实例传递到AddProfile方法之前解析该实例。

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找到,但大部分的重要代码这里分享了。