2014-06-30 33 views
4

我正在使用automapper庫將我的Model轉換爲我的ViewModel。對於每個Model,我創建了一個配置文件,其中我使用CreateMap添加了我的地圖。使用Ninject將參數注入到自動映射器自定義ValueResolver中

我想使用自定義ValueResolver其中它將從IContext獲得登錄的用戶ID,所以我需要通過使用Ninject的IContext的實現。

裏面我的個人資料類:

Mapper.CreateMap<ViewModel, BusinessModel>() 
.ForMember(dest => dest.ManagerId, opt => opt.ResolveUsing<GetManagerResolver>()); 

然後我GetManagerResolver

public class GetManagerResolver : ValueResolver<BusinessModel, int> 
{ 
    private IContext context; 
    public GetManagerResolver(IContext context) 
    { 
     this.context = context; 
    } 

    protected override int GetManagerResolver(BusinessModel source) 
    { 
     return context.UserId; 
    } 
} 

,但我得到這個異常消息{"Type needs to have a constructor with 0 args or only optional args\r\nParameter name: type"}

有關如何使automapper使用ninject創建對象的任何想法?

UPDATE 我的代碼添加automapper配置:調用ResolveUsing

public static class AutoMapperWebConfiguration 
{ 
    public static void Configure() 
    { 
     Mapper.Initialize(cfg => 
     {    
      cfg.AddProfile(new Profile1());   
      cfg.AddProfile(new Profile2()); 

      // now i want to add this line, but how to get access to kernel in static class? 
      // cfg.ConstructServicesUsing(t => Kernel.Get(t)); 
     }); 
    } 
} 

回答

6

可以使用ConstructedBy功能配置Automapper應該如何創建GetManagerResolver

Mapper.CreateMap<ViewModel, BusinessModel>() 
    .ForMember(dest => dest.ManagerId, 
     opt => opt.ResolveUsing<GetManagerResolver>() 
        .ConstructedBy(() => kernel.Get<GetManagerResolver>()); 

或者你可以全局指定您的Ninject內核供Automapper在使用Mapper.Configuration.ConstructServicesUsing方法解析任何類型時使用:

Mapper.Configuration.ConstructServicesUsing((type) => kernel.Get(type)); 
+0

好,現在我怎麼能得到參考'內核'在我的automapper配置類?看到我的問題更新 –

+0

第一:這是一個完全不同的,未經驗證的問題......第二:有多個選項:將它作爲參數傳遞給'Configure'將您的內核存儲在創建它的靜態字段中,等等。 – nemesv

+0

有沒有人設法讓Ninject與ConstructServicesUsing_一起工作? – khorvat

3

我最終什麼事做是爲Automapper創建NinjectModule,我把我所有的automapper配置,並告訴automapper使用Ninject Kernel構造對象。這裏是我的代碼:

public class AutoMapperModule : NinjectModule 
{ 
    public override void Load() 
    { 
     Mapper.Initialize(cfg => 
     { 
      cfg.ConstructServicesUsing(t => Kernel.Get(t)); 

      cfg.AddProfile(new Profile1()); 
      cfg.AddProfile(new Profile2()); 
     }); 
    } 
} 
相關問題