AddAutoMapper does not load all assemblies in asp.net core

别来无恙 提交于 2021-01-29 18:53:05

问题


I have the following code that add automapper to my app.

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    services.AddHttpClient();

    services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
}

The AppDomain.CurrentDomain.GetAssemblies() returns only assemblies that were loaded at the time it is called. I can see that some of my assemblies which contain my mappings have not been yet loaded and as a result mappings are not loaded which returns me errors about missing map types.

How do I get all assemblies referenced by my project?


回答1:


Reference - From official AutoMapper docs

ASP.NET Core

There is a NuGet package to be used with the default injection mechanism described here and used in this project.

You define the configuration using profiles. And then you let AutoMapper know in what assemblies are those profiles defined by calling the IServiceCollection extension method AddAutoMapper at startup:

services.AddAutoMapper(profileAssembly1, profileAssembly2 /*, ...*/);

or marker types:

services.AddAutoMapper(typeof(ProfileTypeFromAssembly1), typeof(ProfileTypeFromAssembly2) /*, ...*/);

Now you can inject AutoMapper at runtime into your services/controllers:

public class EmployeesController {
    private readonly IMapper _mapper;

    public EmployeesController(IMapper mapper) => _mapper = mapper;

    // use _mapper.Map or _mapper.ProjectTo
}


来源:https://stackoverflow.com/questions/58129450/addautomapper-does-not-load-all-assemblies-in-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!