配置Automapper资料类具有参数的构造和Ninject
问题描述:
我使用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
。有什么不同的方法可以解决这个问题吗?
答
我以不同的方式解决了这个问题。我已经从静态迁移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