首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AutoMapper 9泛型扩展静态类

AutoMapper 9泛型扩展静态类
EN

Stack Overflow用户
提问于 2019-09-12 02:26:56
回答 1查看 712关注 0票数 1

我需要一些帮助。

当我让AutoMappar 9停止工作时,我有一个使用Automapper8Maas的泛型类。我找了个解决办法,却找不到人能帮我吗?

代码语言:javascript
复制
using System.Collections.Generic;

namespace Intranet.Services.Extensions {

    internal static class AutoMapperExtensions {

        public static T MapTo<T>(this object value)
        {
            return AutoMapper.Mapper.Map<T>(value);
        }

        public static IEnumerable<T> EnumerableTo<T>(this object value)
        {
            return AutoMapper.Mapper.Map<IEnumerable<T>>(value);
        }
    }
}

T AutoMapper.Mapper.Map(对象源)非静态字段、方法或属性‘Mapper.Map(对象)’(CS0120)需要对象引用。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-10-01 19:05:40

AutoMapper 9希望您使用依赖注入。这给我的遗留项目增加了一个层次的复杂性,我只是不想处理。

因此,我只是反向设计了它之前所做的事情,并为它编写了一个包装器。

代码语言:javascript
复制
public static class MapperWrapper 
{
    private const string InvalidOperationMessage = "Mapper not initialized. Call Initialize with appropriate configuration. If you are trying to use mapper instances through a container or otherwise, make sure you do not have any calls to the static Mapper.Map methods, and if you're using ProjectTo or UseAsDataSource extension methods, make sure you pass in the appropriate IConfigurationProvider instance.";
    private const string AlreadyInitialized = "Mapper already initialized. You must call Initialize once per application domain/process.";

    private static IConfigurationProvider _configuration;
    private static IMapper _instance;

    private static IConfigurationProvider Configuration
    {
        get => _configuration ?? throw new InvalidOperationException(InvalidOperationMessage);
        set => _configuration = (_configuration == null) ? value : throw new InvalidOperationException(AlreadyInitialized);
    }

    public static IMapper Mapper
    {
        get => _instance ?? throw new InvalidOperationException(InvalidOperationMessage);
        private set => _instance = value;
    }

    public static void Initialize(Action<IMapperConfigurationExpression> config)
    {
        Initialize(new MapperConfiguration(config));
    }

    public static void Initialize(MapperConfiguration config)
    {
        Configuration = config;
        Mapper = Configuration.CreateMapper();
    }

    public static void AssertConfigurationIsValid() => Configuration.AssertConfigurationIsValid();
}

要使用它,只需在以前的Mapper调用之前添加MapperWrapper即可。

代码语言:javascript
复制
 MapperWrapper.Mapper.Map<Foo2>(Foo1);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57898956

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档