1. 程式人生 > >ASP.NET.Core中使用AutoMapper

ASP.NET.Core中使用AutoMapper

nvi 創建 reat fin intern stat 中間件 isa addm

首先需要在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創建對象,所以只需添加構造函數即可。

ASP.NET.Core中使用AutoMapper