2016-09-28 81 views
1

我使用Automapper(v5.1.1.0)和Ninject(v3.2.0.0)。我的個人資料類是:配置Automapper資料類具有參數的構造和Ninject

public class ApplicationUserResponseProfile : Profile 
{ 
    public ApplicationUserResponseProfile(HttpRequestMessage httpRequestMessage) 
    { 
     UrlHelper urlHelper = new UrlHelper(httpRequestMessage); 
     CreateMap<ApplicationUser, ApplicationUserResponseModel>() 
      .ForMember(dest => dest.Url, opt => opt.MapFrom(src => urlHelper.Link("GetUserById", new { id = src.Id }))); 
    } 

    public ApplicationUserResponseModel Create(ApplicationUser applicationUser) 
    { 
     return Mapper.Map<ApplicationUserResponseModel>(applicationUser); 
    } 
} 

而且AutoMapperWebConfiguration是:

Mapper.Initialize(cfg => 
     { 
      cfg.AddProfile<ApplicationUserResponseProfile>(); // unable to configure 
     }); 

我也曾嘗試將其綁定到Ninject內核:

var config = new MapperConfiguration(
      c => 
      { 
       c.AddProfile(typeof(ApplicationUserResponseProfile)); 
      }); 
var mapper = config.CreateMapper(); 
kernel.Bind<IMapper>().ToConstant(mapper); 

而且不同的方式:

Mapper.Initialize(cfg => 
     { 
      cfg.ConstructServicesUsing((type) => kernel.Get(type)); 
      cfg.AddProfile(typeof(ApplicationUserResponseProfile)); 
     }); 

但是得到了e RROR以兩種方式 -

此對象

請幫我沒有定義參數的構造函數。我無法配置AutoMapper配置文件類(其中有參數)與Ninject。有什麼不同的方法可以解決這個問題嗎?

回答

1

我以不同的方式解決了這個問題。我已經從靜態遷移automapper而不是Profile的方法。

public class ApplicationUserResponseFactory 
{ 
    private MapperConfiguration _mapperConfiguration; 
    public ApplicationUserResponseFactory(HttpRequestMessage httpRequestMessage) 
    { 
     UrlHelper urlHelper = new UrlHelper(httpRequestMessage); 
     _mapperConfiguration = new MapperConfiguration(cfg => 
     { 
      cfg.CreateMap<ApplicationUser, ApplicationUserResponseModel>() 
       .ForMember(dest => dest.Url, opt => opt.MapFrom(src => UrlHelper.Link("GetUserById", new { id = src.Id }))); 
     }); 

    } 

    public ApplicationUserResponseModel Create(ApplicationUser applicationUser) 
    { 
     return _mapperConfiguration.CreateMapper().Map<ApplicationUserResponseModel>(applicationUser); 
    } 
} 

我已經找到了遷移過程here

相關問題