我正在使用 Automapper
(v5.1.1.0) 和 Ninject
(v3.2.0.0)。我的个人资料类是:
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
});
我还尝试将它绑定(bind)到 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));
});
但是在两个方面都出错了 -
No parameterless constructor defined for this object
请帮帮我。我无法使用 Ninject
配置 AutoMapper
配置文件类(具有参数)。有什么不同的方法可以解决这个问题吗?
最佳答案
我已经用不同的方式解决了这个问题。我已经从静态而不是 Profile
方法迁移了 automapper
。
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
关于c# - 使用参数构造函数和 Ninject 配置 Automapper 配置文件类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39740169/