我有一个 Person 和一个 PersonViewModel。我从 Person => PersonViewModel 创建了一个地图。问题是PersonViewModel 的唯一构造函数需要一个参数(它有一个我想要注入的依赖项),而 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();
}
}
Run Code Online (Sandbox Code Playgroud)
其余的代码是类和接口定义。它们几乎是空的。
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
{
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我为 AutoMapper 提供了 FactoryMethod,但它从未被调用。
当它到达测试的最后一行 (Mapper.Map<...>()) 时,它会抛出一个异常:
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
Run Code Online (Sandbox Code Playgroud)
有什么问题?为什么没有调用 FactoryMethod?
.ConstructUsingServiceLocator()正如 @khorvat 提到的,具体映射缺少哪里。
您也可以直接设置构造函数
.ConstructUsing(source => Method(source.anySourceOptions))
Run Code Online (Sandbox Code Playgroud)
或者正如例外所说:
PersonViewModel,必须有一个带有 0 个参数或只有可选参数的构造函数。你只有一个带有 1 个非可选参数的构造函数
您可以再创建一个不带参数的构造函数:
public PersonViewModel()
{
this.service = new SomeDependency();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2336 次 |
| 最近记录: |