我有一個Person和PersonViewModel。我從Person => PersonViewModel創建了一個映射。問題是,PersonViewModel的唯一構造函數需要一個參數(它有一個依賴項,我想注入),AutoMapper抱怨,因爲它說它需要一個無參數的構造函數。AutoMapper構造服務忽略使用
要解決它,我用了ConstructServicesUsing方法,但我一直沒成功與它:(
爲了說明的情況下,我創建了一個測試給你看我在做什麼。這是非常簡單:
[TestMethod]
public void TestConstructServicesUsing()
{
Mapper.Initialize(configuration =>
{
configuration.ConstructServicesUsing(FactoryMethod);
configuration.CreateMap<Person, PersonViewModel>();
});
Mapper.AssertConfigurationIsValid();
var person = new Person();
var personViewModel = Mapper.Map<Person, PersonViewModel>(person);
}
private object FactoryMethod(Type type)
{
throw new NotImplementedException();
}
}
代碼的其餘部分的類和接口定義它們幾乎空
public class SomeyDependency : ISomeDependency
{
}
public class PersonViewModel
{
private readonly ISomeDependency service;
public PersonViewModel(ISomeDependency service)
{
this.service = service;
}
public string Name { get; set; }
}
public class Person
{
public string Name { get; set; }
}
public interface ISomeDependency
{
}
正如你看到的,我提供AutoMapper一個FactoryMeth。 od,但它永遠不會被調用。
當它到達測試的最後一行(Mapper.Map < ...>()),它拋出一個excepton說:
AutoMapper.AutoMapperMappingException:
Mapping types:
Person -> PersonViewModel
MappingWithContainerTests.Person -> MappingWithContainerTests.PersonViewModel
Destination path:
PersonViewModel
Source value:
MappingWithContainerTests.Person ---> System.ArgumentException: Type needs to have a constructor with 0 args or only optional args
Parameter name: type
什麼問題? 爲什麼不調用FactoryMethod?
我知道這是一個年紀大一點的問題,但在CreateMap <>有一個_.ConstructUsingServiceLocator ()_應該完成這項工作,但在我的情況下它不起作用。 – khorvat
@khorvat +1,在CreateMap <>表達式後面添加.ConstructUsingServiceLocator()使它適用於我,我的情況看起來與OP的示例非常相似。不知何故,我預計映射器將始終使用工廠方法(如果提供的話)。不過,我想知道爲什麼它不適合你。 –