How to Configure AutoMapper Once Per AppDomain

后端 未结 4 1148
别跟我提以往
别跟我提以往 2020-12-24 07:36

My current project with assemblies for the domain model, MVC web application, and unit tests. How can I set up the AutoMapper configuration so that all assemblies reference

4条回答
  •  无人及你
    2020-12-24 08:38

    I tried the code above, but could not get it to work. I modified it a little bit as follows below. I think all that's left to do is to call it via a Bootstrapper from Global.asax. Hope this helps.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    
    using AutoMapper;
    
    namespace Automapping
    {
        public class AutoMappingTypePairing
        {
            public Type SourceType { get; set; }
            public Type DestinationType { get; set; }
        }
    
        public class AutoMappingAttribute : Attribute 
        {
            public Type SourceType { get; private set; }
    
            public AutoMappingAttribute(Type sourceType)
            {
                if (sourceType == null) throw new ArgumentNullException("sourceType");
                SourceType = sourceType; 
            }
        }
    
        public static class AutoMappingEngine
        {
            public static void CreateMappings(Assembly a)
            {
                IList autoMappingTypePairingList = new List();
    
                foreach (Type t in a.GetTypes())
                {
                    var amba = t.GetCustomAttributes(typeof(AutoMappingAttribute), true).OfType().FirstOrDefault();
    
                    if (amba != null)
                    {
                        autoMappingTypePairingList.Add(new AutoMappingTypePairing{ SourceType = amba.SourceType, DestinationType = t});
                    }
                } 
    
                foreach (AutoMappingTypePairing mappingPair in autoMappingTypePairingList) 
                {
                    Mapper.CreateMap(mappingPair.SourceType, mappingPair.DestinationType);
                }
            }
        }
    }
    

    And I use it like this to associate a source with a destination pairing:

    [AutoMapping(typeof(Cms_Schema))]
    public class Schema : ISchema
    {
        public Int32 SchemaId { get; set; }
        public String SchemaName { get; set; }
        public Guid ApplicationId { get; set; }
    }
    

    Then to Create the mappings automagically, I do this:

            Assembly assembly = Assembly.GetAssembly(typeof([ENTER NAME OF A TYPE FROM YOUR ASSEMBLY HERE]));
    
            AutoMappingEngine.CreateMappings(assembly);
    

提交回复
热议问题