How to scan and auto-configure profiles in AutoMapper?

后端 未结 8 695
花落未央
花落未央 2020-12-24 02:50

Is there any way to auto-configue Automapper to scan for all profiles in namespace/assembly? What I would like to do is to add mapping profiles to AutoMapper from given asse

8条回答
  •  渐次进展
    2020-12-24 03:03

    In version 9 of AutoMapper it can be done this way

    var configuration = new MapperConfiguration(cfg =>
    {
        // Add all Profiles from the Assembly containing this Type
        cfg.AddMaps(typeof(MyApp.SomeClass));
    });
    

    If you are using ASP.NET Core there is a helper extension to register all Profiles in Startup.ConfigureServices

    // UI project
    services.AddAutoMapper(Assembly.GetExecutingAssembly());
    

    or

    // Another assembly that contains a type
    services.AddAutoMapper(Assembly.GetAssembly(typeof(MyApp.SomeClass)));
    

提交回复
热议问题