2016-09-28 2 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

Смежные вопросы