无法解析服务 AutoMapper

service AutoMapper can't be resolved

这可能与 Unable to resolve service for type 'AutoMapper.Mapper' 重复,但自从有人提出这个问题以来已经有一年了,我认为我的设置略有不同。

我有一个 .NET 5.0 webapi 项目,它有一个启动 class 看起来像这样

public class Startup
{
    private readonly IConfiguration _config;
    public Startup(IConfiguration config)
    {
        _config = config;
    }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddApplicationServices(_config); //This is to keep the Startup class clean
        services.AddControllers();
        services.AddCors();
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "API", Version = "v1" });
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseSwagger();
            app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "ts.API v1"));
        }

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod()
            .WithOrigins("https://localhost:4200"));

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

我有一个单独的 ApplicationServiceExtension 来处理服务。这就是class。这是我调用 AddAutoMapper 的地方。我试过跳过它并直接将其放入 Startup.cs 但这并没有什么不同。

public static class ApplicationServiceExtensions
{
    public static IServiceCollection AddApplicationServices(this IServiceCollection services, IConfiguration config)
    {
        services.AddScoped<IUserRepository, UserRepository>();
        services.AddAutoMapper(typeof(AutoMapperProfiles).Assembly);
        services.AddDbContext<DataContext>(options =>
        {
            options.UseSqlServer(config.GetConnectionString("DefaultConnection"),  b => b.MigrationsAssembly("ts.Data"));
        });

        return services;
    }
}

在一个单独的项目(一个控制台项目)中,我处理所有与来自数据库的数据有关的事情。这也是我使用扩展 IUserRepositoryUserRepository.cs 的地方。我在那里保存了所有 DTO 以及我的 AutoMapper 配置文件。基本上,我什至不需要在我的 webapi 项目中使用 AutoMapper,但除了将它添加到 Startup.cs 之外,我不知道如何获得它 运行。也许我应该提一下,我是 .NET core/5.0 的新手,之前没有真正使用过 AutoMapper,更不用说从头开始设置它了。

我得到的错误看起来像这样

Unhandled exception. System.AggregateException: Some services are not able to be constructed
(Error while validating the service descriptor 'ServiceType: ts.Data.Interfaces.IUserRepository Lifetime: 
Scoped ImplementationType: ts.Data.Repositories.UserRepository': Unable to resolve service for type 'AutoMapper.Mapper' 
while attempting to activate 'ts.Data.Repositories.UserRepository'.)

以防万一你想看,这是我的 UserRepository。

public class UserRepository : IUserRepository
{
    private readonly DataContext _context;
    private readonly Mapper _mapper;
    public UserRepository(DataContext context, Mapper mapper)
    {
        _mapper = mapper;
        _context = context;
    }

    public async Task<IEnumerable<UserDto>> GetAllAsync()
    {
        return await _context.Users
            .ProjectTo<UserDto>(_mapper.ConfigurationProvider)
            .ToListAsync();
    }
}

如果有人知道我为什么会收到此错误,我将非常感谢您的帮助。我已经被这个问题困扰太久了,它可能也非常简单。

删除 Assembly 并尝试。

services.AddAutoMapper(typeof(AutoMapperProfiles));

Startup.cs的末尾添加以下方法

    private static void RegisterServices(IServiceCollection services, IConfiguration config)
    {
        ApplicationServiceExtensions.AddApplicationServices(services, config);
    }

调用 RegisterServices 并在 ConfigureServices 方法结束时传递 services_config

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddCors();
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "API", Version = "v1" });
        });

        RegisterServices(services, _config);
    }

并使AddApplicationServices无效,将AddAutoMapper移动到顶部

public static class ApplicationServiceExtensions
{
    public static void AddApplicationServices(IServiceCollection services, IConfiguration config)
    {
        services.AddAutoMapper(typeof(AutoMapperProfiles));
        services.AddScoped<IUserRepository, UserRepository>();
        services.AddDbContext<DataContext>(options =>
        {
            options.UseSqlServer(config.GetConnectionString("DefaultConnection"),  b => b.MigrationsAssembly("ts.Data"));
        });
    }
}

AutoMapperProfiles应该继承Profile

public class AutoMapperProfiles : Profile
{
    public AutoMapperProfiles()
    {
        CreateMap<Initiative, InitiativeViewModel>();
    }
}

尝试像这样添加自动映射器:

services.AddAutoMapper(configuration => configuration
    .AddProfile<AutoMapperProfiles>(), typeof(Startup));

并在您的 UserRepository 中注入 IMapper 而不是 Mapper。