使用Automapper动态初始化对象属性?

时间:2013-11-06 11:07:00

标签: c# performance reflection automapper

我希望初始化一组看起来有点像这样的视图模型对象:

public class ModelA
{
    public GraphModel SomeGraph { get; set; }
    public GraphModel SomeGraph2 { get; set; }
    public TableModel SomeTable { get; set; }
    public GraphModel SomeGraph3 { get; set; }
}

public class ModelB
{
    public GraphModel SomeGraph { get; set; }
    public TableModel SomeGraph2 { get; set; }
    public TableModel SomeTable { get; set; }
    public FieldModel SomeField { get; set; }
}

现在我可以用new TableModel()new GraphModel()显式初始化它们,但我真的宁愿这是动态完成的,所以我构建了一个迭代所有属性的过程并用一组预定义填充它们每种类型的初始化器:

new Dictionary<Type, Func<object>>
    {
        {typeof (...), () => new ...{x = y}},
        {typeof (...), () => new ...{z = y, c = g}},
        {typeof (...), () => new ...{z = q}},
        {typeof (...), () => new ...{x = y}},
    };

由于我有很多并且反射成本很高,我想知道如果在AutoMapper中使用某种默认的基于类型的映射可以实现相同,因为我猜它最终会使用缓存的预编译表达式

1 个答案:

答案 0 :(得分:0)

您是否考虑过使用T4为AutoMapper配置生成一些Factory或者只是BeforeMap方法? 假设您有以下类,其中包含所有初始值设定项。

namespace App
{
    public class Defaults
    {
        private static Dictionary<Type, Func<object>> _initializer = new Dictionary<Type, Func<object>>
        {
            {typeof (FieldModel), () => new FieldModel {X = "X"}},
            {typeof (TableModel), () => new TableModel {Y = "Y", Z = "Z"}}
        };

        public static Dictionary<Type, Func<object>> Initializer
        {
            get { return _initializer; }
            set { _initializer = value; }
        }
    }
}

然后添加如下文字模板:

enter image description here

由于转换,我们得到一个包含以下内容的文件:

public class Factory
{
    public App.ModelA Initizlize(App.ModelA source)
    {
         source.SomeTable = (App.TableModel)App.Defaults.Initializer[typeof(App.TableModel)].Invoke();
         return source;
    }
    public App.ModelB Initizlize(App.ModelB source)
    {
         source.SomeGraph2 = (App.TableModel)App.Defaults.Initializer[typeof(App.TableModel)].Invoke();
         return source;
    }
}

Here是关于T4的非常好的资源。