【问题标题】:Automatic discovery of automapper configurations自动发现自动映射器配置
【发布时间】:2012-07-28 06:54:30
【问题描述】:

当您在 MVC 中创建控制器时,您无需为它进行任何额外的注册。添加区域也是如此。只要您的 global.asax 有 AreaRegistration.RegisterAllAreas() 调用,就不需要额外的设置。

使用 AutoMapper,我们必须使用某种CreateMap<TSource, TDestination> 调用来注册映射。可以使用静态 Mapper.CreateMap 显式执行这些操作,或者从 AutoMapper.Profile 类派生,覆盖 Configure 方法,然后从那里调用 CreateMap

在我看来,应该能够扫描程序集以查找从 Profile 扩展的类,就像 MVC 扫描从 Controller 扩展的类一样。有了这种机制,难道不应该简单地通过创建一个派生自Profile的类来创建映射吗?是否存在任何此类库工具,或者自动映射器中是否内置了一些东西?

【问题讨论】:

    标签: asp.net-mvc reflection automapper automapper-2 auto-registration


    【解决方案1】:

    我不知道这样的工具是否存在,但是写一个应该很简单:

    public static class AutoMapperConfiguration
    {
        public static void Configure()
        {
            Mapper.Initialize(x => GetConfiguration(Mapper.Configuration));
        }
    
        private static void GetConfiguration(IConfiguration configuration)
        {
            var assemblies = AppDomain.CurrentDomain.GetAssemblies();
            foreach (var assembly in assemblies)
            {
                var profiles = assembly.GetTypes().Where(x => x != typeof(Profile) && typeof(Profile).IsAssignableFrom(x));
                foreach (var profile in profiles)
                {
                    configuration.AddProfile((Profile)Activator.CreateInstance(profile));
                }
            }
        }
    }
    

    然后在您的Application_Start 中您可以自动接线:

    AutoMapperConfiguration.Configure();
    

    【讨论】:

    • +1 代码。你是说.Where(x => x => x != typeof(...,还是.Where(x => x != typeof(...
    【解决方案2】:

    作为对@Darin Dimitrov 答案的轻微改进,在 AutoMapper 5 中,您可以给它一个要扫描的组件列表,如下所示:

    //--As of 2016-09-22, AutoMapper blows up if you give it dynamic assemblies
    var assemblies = AppDomain.CurrentDomain.GetAssemblies()
                        .Where(x => !x.IsDynamic);
    //--AutoMapper will find all of the classes that extend Profile and will add them automatically    
    Mapper.Initialize(cfg => cfg.AddProfiles(assemblies));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-10
      • 2014-11-19
      • 1970-01-01
      相关资源
      最近更新 更多