【问题标题】:Using Profiles in Automapper to map the same types with different logic with DI support for CustomValue Resolvers使用 Automapper 中的配置文件来映射具有不同逻辑的相同类型,并支持自定义值解析器的 DI
【发布时间】:2018-08-17 21:25:55
【问题描述】:

我正在尝试在 .net core 1.0.1 应用程序中使用 automapper 来根据配置文件映射具有不同逻辑的类型。我也有一些自定义解析器。我无法在自定义解析器中获得 DI 支持。这是我创建映射器的代码。

private IMapper CreateMapper(string srcFormName)
{
    switch (srcFormName)
    {
        case "app1":
            {
                var configuration1 = new MapperConfiguration(cfg =>
                {
                    cfg.AddProfile<App1Profile>();
                });
                 return configuration1.CreateMapper();
            }
        case "app2":
            {
                var configuration2 = new MapperConfiguration(cfg =>
                {
                    cfg.AddProfile<App2Profile>();
                });
                return configuration2.CreateMapper();
            }
        default:
            return null;
    }
}

我正在使用包https://www.nuget.org/packages/AutoMapper.Extensions.Microsoft.DependencyInjection/2.0.1,下面的行已添加到 Startup.cs

 services.AddAutoMapper();

我需要一个像下面这样的自定义解析器

public class NameResolver : IValueResolver<MyType1, MyType2, string>
{
    private IContextInfo _contextInfo;

    //public NameResolver()
    //{

    //}

    public NameResolver(IContextInfo contextInfo)
    {
        _contextInfo = contextInfo;
    }

    public string Resolve(ApplicationForm source, StpApplication destination,
        string destMember, ResolutionContext context)
    {
        _contextInfo.RulesExecuted.Add(DateTime.Now.ToString());
        return source.FirstName + " " + source.MiddleName + " " + source.LastName;
    }
}

但是当我尝试映射时,我得到了一个异常,例如无参数构造函数不存在(在我的解析器上)并且无法映射。我相信这可能是因为创建了我自己的映射器配置,但是我不知道在不创建自己的配置的情况下使用多个配置文件。请帮我。

【问题讨论】:

    标签: asp.net-core dependency-injection automapper


    【解决方案1】:

    当使用来自AutoMapper 的扩展将其与来自 .NET Core 的本机 IoC 集成时,您无需自己应用映射器配置。

    只需将程序集传递给函数

    services.AddAutoMapper(myAssembliesContainingAutoMapperTypes);
    

    如果类型与您的 Startup-Class 在同一个项目中,请这样做

    services.AddAutoMapper(typeof(Startup).Assembly);
    

    现在它将注册profiles, valueresolver and so on automatically。 它还有一个扩展方法可以将映射器配置传递给它。这将被使用并扩展。

    services.AddAutoMapper(config => { ... }, typeof(Startup).Assembly);
    

    如果您不传递包含您的解析器和其他自动映射器类型的程序集,您也可以手动注册您的解析器。

    services.AddTransiert(typeof(NameResolver));
    

    第一种方法更好并且推荐,您永远不会自己注册东西。这就是建立这个库的原因。只需传递包含您的类型的程序集:)

    【讨论】:

    • 希望你也理解我的要求。在这种风格中,我如何指定用于映射的配置文件。创建自己的配置是我知道的唯一方法。如果有其他方法,请告诉我。
    • 是的,我告诉过你,你可以将映射器配置传递给扩展方法。读得好。您还可以提供有关为什么需要定义应使用哪些配置文件的更多信息。也许这是一个设计缺陷。
    • 如果我只能在运行时确定需要运行哪个映射配置文件,我不知道如何处理
    • 你可以将配置传递给方法,只要看我提供的例子并尝试在github上挖掘代码以了解发生了什么。
    猜你喜欢
    • 2011-01-12
    • 1970-01-01
    • 1970-01-01
    • 2016-08-13
    • 2018-11-15
    • 2019-03-01
    • 2017-04-16
    • 2015-09-22
    • 1970-01-01
    相关资源
    最近更新 更多