简体   繁体   English

AutoMapper如何避免初始化

[英]AutoMapper how to avoid initialization

How do I avoid requiring code like this: 我如何避免要求这样的代码:

public static class BusinessLogicAutomapper
{
    public static bool _configured;

    public static void Configure()
    {
        if (_configured)
            return;

        Mapper.CreateMap<Post, PostModel>();
        _configured = true;
    }
}

in my BL assembly, and having to call Configure() from my Global.asax in my MVC application? 在我的BL程序集中,并且必须从我的MVC应用程序中的Global.asax调用Configure()

I mean, I expect a call like this: 我的意思是,我期待这样的电话:

    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;
    }

to Mapper.Map<TIn,TOut> to produce the mapper if it isn't in existance, instead of having to create it myself manually (I shouldn't even know about this inner working). Mapper.Map<TIn,TOut>生成映射器(如果它不存在),而不是自己手动创建它(我甚至不知道这个内部工作)。 How can I work around declaratively creating mappers for AutoMapper? 我如何解决为AutoMapper声明性地创建映射器?

A solution that's natural to AutoMapper would be desired, but an extension or some architectural change in order to avoid this initialization would work too. 需要一个对AutoMapper来说很自然的解决方案,但是为了避免这种初始化,扩展或一些架构改变也会起作用。

I'm using MVC 3, .NET 4, and no IoC/DI (yet, at least) 我正在使用MVC 3,.NET 4,没有IoC / DI(至少)

I completely misunderstood what you were trying to do in my original answer. 我完全误解了你在原来的答案中想要做的事情。 You can accomplish what you want by implementing part of the functionality of AutoMapper using reflection. 您可以通过使用反射实现AutoMapper的部分功能来完成您想要的任务。 It will be of very limited utility and the more you extend it, the more like AutoMapper it will be so I'm not sure that there's any long term value to it. 它的实用性非常有限,你扩展得越多,它就越像AutoMapper,所以我不确定它有什么长期价值。

I do use a small utility like what you are wanting to automate my auditing framework to copy data from a entity model to its associated audit model. 我确实使用了一个小实用程序,就像你想要自动化我的审计框架一样,将数据从实体模型复制到相关的审计模型。 I created it before I started using AutoMapper and haven't replaced it. 我在开始使用AutoMapper之前创建了它并且没有替换它。 I call it a ReflectionHelper, the below code is a modification of that (from memory) -- it only handles simple properties but can be adapted to support nested models and collections if need be. 我把它称为ReflectionHelper,下面的代码是对它的修改(来自内存) - 它只处理简单的属性,但可以根据需要调整以支持嵌套模型和集合。 It's convention-based, assuming that properties with the same name correspond and have the same type. 它是基于约定的,假设具有相同名称的属性对应且具有相同的类型。 Properties that don't exist on the type being copied to are simply ignored. 简单地忽略要复制到的类型上不存在的属性。

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;
      }

Used as 用作

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

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

Original 原版的

I do my mapping in a static constructor. 我在静态构造函数中进行映射。 The mapper is initialized the first time the class is referenced without having to call any methods. 第一次引用类时初始化映射器而不必调用任何方法。 I don't make the logic class static, however, to enhance its testability and the testability of classes using it as a dependency. 但是,我不会将逻辑类设置为静态,以增强其可测试性和使用它作为依赖项的类的可测试性。

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

check out Automapper profiles. 查看Automapper配置文件。

I have this setup in my Global.asax - it runs once statically so everything is setup at runtime ready to go. 我在我的Global.asax中有这个设置 - 它静态运行一次所以一切都在运行时准备好了。

I also have 1 unit test which covers all maps to check they are correct. 我还有1个单元测试,覆盖所有地图以检查它们是否正确。

A good example of this is Ayendes Raccoon Blog 一个很好的例子是Ayendes Raccoon Blog

https://github.com/ayende/RaccoonBlog https://github.com/ayende/RaccoonBlog

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM