我正在使用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));
});
}
}
好,現在我怎麼能得到參考'內核'在我的automapper配置類?看到我的問題更新 –
第一:這是一個完全不同的,未經驗證的問題......第二:有多個選項:將它作爲參數傳遞給'Configure'將您的內核存儲在創建它的靜態字段中,等等。 – nemesv
有沒有人設法讓Ninject與ConstructServicesUsing_一起工作? – khorvat