Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 自动映射从静态API迁移_C#_Asp.net_Automapper - Fatal编程技术网

C# 自动映射从静态API迁移

C# 自动映射从静态API迁移,c#,asp.net,automapper,C#,Asp.net,Automapper,这个变化打破了我的系统 在更新之前,我使用: =>Startup.cs public class Startup { public Startup(IHostingEnvironment env) { ... MyAutoMapperConfiguration.Configure(); } } =>MyAutoMapperConfiguration.cs public class MyAutoMapperConfiguration { p

这个变化打破了我的系统

在更新之前,我使用:

=>Startup.cs

public class Startup
{
    public Startup(IHostingEnvironment env)
    {
    ...
        MyAutoMapperConfiguration.Configure();
    }
}
=>MyAutoMapperConfiguration.cs

public class MyAutoMapperConfiguration
{
    public static void Configure()
    {
        Mapper.Initialize(a =>
        {
            a.AddProfile<AbcMappingProfile>();
            a.AddProfile<XyzMappingProfile>();
            a.AddProfile<QweMappingProfile>();
        });
    }
}
公共类MyAutoMapperConfiguration
{
公共静态void Configure()
{
Mapper.Initialize(a=>
{
a、 AddProfile();
a、 AddProfile();
a、 AddProfile();
});
}
}
==>AbcMappingProfile.cs

public class AbcMappingProfile : Profile
{
    protected override void Configure()
    {
        Mapper.CreateMap<AbcEditViewModel, Abc>();
        Mapper.CreateMap<Abc, AbcEditViewModel>();
        ...
    }
}
公共类AbcMappingProfile:Profile
{
受保护的覆盖无效配置()
{
CreateMap();
CreateMap();
...
}
}
错误:

“Mapper.CreateMap()”已过时:“将在5.0版中删除静态API。使用MapperConfiguration实例并根据需要静态存储。使用CreateMapper创建映射器实例。”

我可以使用Mapper.Map。现在,我如何使用它来代替:

Mapper.CreateMap<AbcEditViewModel, Abc>();

Mapper.CreateMap)

使用IMapperConfigurationExpression扩展来代替自动映射配置文件:

映射配置:

public static class AutoMapperConfig
{
    public static IMapperConfigurationExpression AddAdminMapping(
        this IMapperConfigurationExpression configurationExpression)
    {
        configurationExpression.CreateMap<Job, JobRow>()
            .ForMember(x => x.StartedOnDateTime, o => o.PreCondition(p => p.StartedOnDateTimeUtc.HasValue))
            .ForMember(x => x.StartedOnDateTime, o => o.MapFrom(p => p.StartedOnDateTimeUtc.Value.DateTime.ToLocalTime()))
            .ForMember(x => x.FinishedOnDateTime, o => o.PreCondition(p => p.FinishedOnDateTimeUtc.HasValue))
            .ForMember(x => x.FinishedOnDateTime, o => o.MapFrom(p => p.FinishedOnDateTimeUtc.Value.DateTime.ToLocalTime()));

        return configurationExpression;
    }
}

依赖注入给我的遗留项目增加了一个我不想处理的复杂程度。由于使用许多不同的技术调用同一个库,Webforms、MVC、Azure服务等

依赖注入也会迫使我重写几个方法或传递一个IMapper

所以我只是对它在8.0中的工作进行了反向工程,并为它编写了一个包装器

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();
}
然后,您所要做的就是在所有静态调用之前添加MapperWrapper。一切都和以前一样

 MapperWrapper.Mapper.Map<Foo2>(Foo1);
MapperWrapper.Mapper.Map(Foo1);
Ben Walters:依赖注入为 我不想处理的遗留项目

此外,还可以使用语句应用类别名 无需更改代码,只需更改using语句

为类定义using指令和using别名:

--

.您的类实现的兼容性

名称空间自动映射
{
公共类映射器
{
公共静态无效初始化(操作配置)
{
...
}
}

}
而不是Mapper.Initialize(?我在链接中找不到是的,在Startup.cs中如何配置AutoMapper以及如何在控制器中使用AutoMapper上存在很多困惑。现在必须注入吗?不必注入,但本着DI的精神(即.NET core正在尝试推广)也许应该是这样。很高兴我有时从第三方抽象类。这意味着我只需要更新很少的引用。在这种情况下,什么是
服务
,我如何将映射器git到我的MVC控制器中?@PetrusTheron services是
IServiceCollection
,您可以将它注入到
public void配置服务中ices(iSeries收集服务)
方法,由Asp.net Core FW提供。
        var mappingConfig = new AutoMapper.MapperConfiguration(cfg =>
        {
            cfg.AddAdminMapping();
        });

        services.AddSingleton(x => mappingConfig.CreateMapper());
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();
}
public static class AutoMapperConfig
{
    public static void Configure()
    {
        MapperWrapper.Initialize(cfg =>
        {
            cfg.CreateMap<Foo1, Foo2>();              
        });

        MapperWrapper.AssertConfigurationIsValid();
    }
}
AutoMapperConfig.Configure();
 MapperWrapper.Mapper.Map<Foo2>(Foo1);