ASP.NET.Core中使用AutoMapper

weixin_34223655發表於2017-12-22
 

  首先需要在NuGet中引用AutoMapper的類庫

install-package   AutoMapper
install-package   AutoMapper.Extensions.Microsoft.DependencyInjection

然後建立好要進行轉換的類

public class User
{
        public int ID { get; set; }
        public string Name { get; set; }
}
public class UserDto
{
        public int ID { get; set; }
        public string Name { get; set; }
}

  然後再建立一個標誌介面IProfile

internal interface IProfile
    {
    }

   接下來建立一個類來繼承AutoMapper的Profile類與實現剛才建立的標誌介面IProfile,並且在建構函式中配置關係對映

 public class MyProfile: Profile,IProfile
    {
        public MyProfile()
        {
            CreateMap<User, UserDto>();
            CreateMap<UserDto, User>();
        }
       
    }

  然後再建立一個類來註冊關係對映

public class Mappings
    {
        public static void RegisterMappings()
        {
            //獲取所有IProfile實現類
            var allType =
            Assembly
               .GetEntryAssembly()//獲取預設程式集
               .GetReferencedAssemblies()//獲取所有引用程式集
               .Select(Assembly.Load)
               .SelectMany(y => y.DefinedTypes)
               .Where(type => typeof(IProfile).GetTypeInfo().IsAssignableFrom(type.AsType()));

            foreach (var typeInfo in allType)
            {
                var type = typeInfo.AsType();
                if (type.Equals(typeof(IProfile)))
                {
                    //註冊對映
                    Mapper.Initialize(y =>
                    {
                        y.AddProfiles(type); // Initialise each Profile classe
                    });
                }
            }
        }

    }

 從上面程式碼可以看出使用標誌介面來判斷註冊對映類進行註冊對映,

 最後只需在Startup類的ConfigureServices方法中新增服務和將Mappings新增到中介軟體即可使用

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddAutoMapper();
            services.AddMvc();
            
        }
 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            Mappings.RegisterMappings();
        }

 然後就可以使用automapper,

public class ValuesController : Controller
    {
        
        private IMapper _mapper { get; set; }
        public ValuesController([FromServices]IMapper mapper)
        {
            this._mapper = mapper;
        }

        // GET api/values
        [HttpGet]
        public UserDto Get()
        {
            User user = new User()
            {
                ID = 1,
                Name = "狗娃"
            };
            var dto = Mapper.Map<User, UserDto>(user);
            return dto;
        }
}

  因為core使用DI建立物件,所以只需新增建構函式即可。

相關文章