Dug*_*all 5

使用AutoMapper也有一些缺点,其中一些缺点通常适用于按约定进行编程(与显式编写代码相反)。

假设您有两个C#类-

namespace MyDtoNamespace {
    public class MyClass {
        public int Id { get; set; }
}}

namespace MyBusinessLayerNamespace {
    public class MyClass {
        public int Id { get; set; }
}}
Run Code Online (Sandbox Code Playgroud)

AutoMapper可以很好地在这两个类之间进行映射,而无需进行显式配置。

但是稍后,例如,开发人员考虑将这些Id属性之一重命名为其他内容,例如

namespace MyBusinessLayerNamespace {
    public class MyClass {
        public int MyNewIdentifierVariableName { get; set; }
}}
Run Code Online (Sandbox Code Playgroud)

我在Visual Studio中仔细搜索了引用,并考虑了重命名对这些引用的影响-但是由于MyDtoNamespace.MyClass.Id没有显式引用MyBusinessLayerNamespace.MyClass.Id,因此我从未看到过。

当Visual Studio或其他工具为我在解决方案中自动重命名所有出现的变量时,AutoMapper映射就会中断。

我只能在运行时发现它,没有编译时问题。理想情况下,我可以用单元测试来验证我的映射是否如我所愿,但是即使如此,重构期间潜在的运行时错误也是更喜欢编写显式映射代码的一个很好的理由。

我当然不是在争论完全避免使用AutoMapper,只是指出按照惯例进行编程存在一个主要问题。