c# - 使用参数构造函数和 Ninject 配置 Automapper 配置文件类

标签 c# asp.net-mvc ninject automapper-5

我正在使用 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/

相关文章:

CSS 条件注释不起作用(更新为 : IE specific css? )

asp.net-mvc-2 - 使用 Ninject 的 HttpHandler 属性注入(inject)返回 null

dependency-injection - 忍者2.0 : Property Injection without attribute

c# - 将 .txt 文件中的字符串分隔到不同的文本框

c# - 从对象中读取验证属性

c# - 为什么这个 Lucene.Net 查询会失败?

asp.net-mvc - MVC4 输入字段占位符

c# - 反方差的常见编程用途是什么?

c# - 以不同的方式使用 Razor View 引擎

c# - 通用存储库、DI、聚合根