2010-03-08 61 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找到,但大部分的重要代碼這裏分享了。