Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/visual-studio-code/3.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# 在运行时动态构建配置_C#_Automapper 5 - Fatal编程技术网

C# 在运行时动态构建配置

C# 在运行时动态构建配置,c#,automapper-5,C#,Automapper 5,我们有一个旧的(手动启动的)系统,它使用反射将一个模型映射到另一个模型。这将使用模型上的属性来确定需要传输的内容。此转换在运行时在共享项目的基类内处理 我正在考虑用Automapper的一个实现在较低的级别上替换它-在测试过程中,在大容量下,这似乎要快得多 我想做的是继续使用遗留机制生成映射以保持一致性。我可以使用以下代码成功完成此操作: public static IMapper CreateMap() { var configuration = new MapperConfi

我们有一个旧的(手动启动的)系统,它使用反射将一个模型映射到另一个模型。这将使用模型上的属性来确定需要传输的内容。此转换在运行时在共享项目的基类内处理

我正在考虑用Automapper的一个实现在较低的级别上替换它-在测试过程中,在大容量下,这似乎要快得多

我想做的是继续使用遗留机制生成映射以保持一致性。我可以使用以下代码成功完成此操作:

public static IMapper CreateMap()
{
        var configuration = new MapperConfiguration(
                 BuildMapForModel<ModelA, ModelB>);

    var map = configuration.CreateMapper();

    return map;
}

public static void BuildMapForModel<TIn, TOut>(IMapperConfigurationExpression config)
{
    var expression = config.CreateMap<TIn, TOut>();

    //Build the mapping with reflection.
    foreach (var propertyInfo in typeof(TOut).GetProperties())
    {
        var attribute = propertyInfo.GetCustomAttribute(typeof(CustomMappingAttribute)) as CustomMappingAttribute;

        if (attribute == null)
        {
            expression.ForMember(propertyInfo.Name, opt => opt.Ignore());
        }
        else
        {
            var sourceproperty = attribute.SourcePropertyName;

            expression.ForMember(propertyInfo.Name, map => map.MapFrom(sourceproperty));
        }
    }

    expression.ReverseMap();
}
但是,
MapperConfiguration
似乎不允许在创建映射后添加映射,也不允许使用无参数构造函数

如何设置它,使我只在必要时运行映射代码,而不必每次都运行它

private static MapperConfiguration Configuration { get; set; }

public static TOut Convert<TIn, TOut>(TIn item)
{
    if (Configuration == null)
    {
        //Create a new configuration object.
    }

    if (Configuration.FindTypeMapFor<TIn, TOut>() == null)
    {
        //Add a mapping to the configuration - via BuildMapForModel.
    }

    var map = Configuration.CreateMapper();
    return map.Map<TIn, TOut>(item);

}