0

这可能是Unable to resolve service for type 'AutoMapper.Mapper'的副本,但自从被问到这已经一年了,我认为我的设置略有不同。

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

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 来处理服务。这就是那堂课。这就是我调用 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;
    }
}

在一个单独的项目(控制台项目)中,我处理与来自数据库的数据有关的所有事情。这也是我使用UserRepository.cs扩展的地方IUserRepository。我把我所有的 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();
    }
}

如果有人知道我为什么会收到此错误,我将非常感谢您的帮助。我一直坚持这个太久了,它可能也很简单。

4

2 回答 2

0

删除Assembly并尝试。

services.AddAutoMapper(typeof(AutoMapperProfiles));

在最后Startup.cs添加以下方法

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

在方法结束时调用并RegisterServices传递。services_configConfigureServices

    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>();
    }
}
于 2021-05-07T18:01:29.333 回答
-1

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

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

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

于 2021-05-07T18:28:40.667 回答