如何避免初始化



如何避免这样的代码:

public static class BusinessLogicAutomapper
{
    public static bool _configured;
    public static void Configure()
    {
        if (_configured)
            return;
        Mapper.CreateMap<Post, PostModel>();
        _configured = true;
    }
}

在我的BL组装,并不得不从我的Global.asax在我的MVC应用程序调用Configure() ?

我的意思是,我期待这样的电话:

    public PostModel GetPostById(long id)
    {
        EntityDataModelContext context = DataContext.GetDataContext();
        Post post = context.Posts.FirstOrDefault(p => p.PostId == id);
        PostModel mapped = Mapper.Map<Post, PostModel>(post);
        return mapped;
    }

Mapper.Map<TIn,TOut>生成映射器,如果它不存在,而不是必须手动创建它自己(我甚至不应该知道关于这个内部工作)。如何为AutoMapper声明式地创建映射器?

我们需要一个对AutoMapper来说很自然的解决方案,但是为了避免这个初始化,一个扩展或一些架构上的改变也会起作用。

我使用MVC 3, .NET 4,没有IoC/DI(至少,现在)

我完全误解了你在我最初的回答中想要做的事情。您可以通过使用反射实现AutoMapper的部分功能来完成您想要的功能。它的效用将非常有限,你越扩展它,它就越像AutoMapper,所以我不确定它是否有任何长期价值。

我确实使用了一个小实用程序,就像你想要自动审计框架一样,将数据从实体模型复制到其相关的审计模型。我在开始使用AutoMapper之前创建了它,并且没有替换它。我称它为ReflectionHelper,下面的代码是对它的修改(来自内存)——它只处理简单的属性,但可以根据需要进行调整以支持嵌套模型和集合。它是基于约定的,假设具有相同名称的属性对应并且具有相同的类型。复制到的类型中不存在的属性将被忽略。

public static class ReflectionHelper
{
      public static T CreateFrom<T,U>( U from )
          where T : class, new
          where U : class
      {
            var to = Activator.CreateInstance<T>();
            var toType = typeof(T);
            var fromType = typeof(U);
            foreach (var toProperty in toType.GetProperties())
            {
                var fromProperty = fromType.GetProperty( toProperty.Name );
                if (fromProperty != null)
                {
                   toProperty.SetValue( to, fromProperty.GetValue( from, null), null );
                }
            }
            return to;
      }

作为

    var model = ReflectionHelper.CreateFrom<ViewModel,Model>( entity );
    var entity = ReflectionHelper.CreateFrom<Model,ViewModel>( model );
原来

我在静态构造函数中进行映射。映射器在类第一次被引用时初始化,而不必调用任何方法。但是,我没有将逻辑类设置为静态,以增强它的可测试性以及使用它作为依赖的类的可测试性。

public class BusinessLogicAutomapper
{
    static BusinessLogicAutomapper
    {
        Mapper.CreateMap<Post, PostModel>();
        Mapper.AssertConfigurationIsValid();
    }
}

查看Automapper配置文件

我在全局设置中设置了这个。Asax -它静态运行一次,所以在运行时一切都准备好了。

我也有一个单元测试,涵盖所有的地图,以检查他们是正确的。

一个很好的例子是Ayendes Raccoon Blog https://github.com/ayende/RaccoonBlog

最新更新