简体   繁体   中英

AddAutoMapper does not load all assemblies in asp.net core

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?

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM