ASP.NET.Core中使用AutoMapper

來源:互聯網
上載者:User

標籤:equals   ref   sas   配置   auto   asp.net   gis   mic   public   

 

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

install-package   AutoMapperinstall-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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.