首页 > 解决方案 > 尝试激活 'xxx.Infrastructure.TagRepository' 时无法解析类型 xxx.'Infrastructure' 的服务

问题描述

我收到以下错误。我正在使用 .Net Core Web API。

处理请求时发生未处理的异常。InvalidOperationException:尝试激活“xxx.Infrastructure.Repository.TagRepository”时,无法解析“xxx.Infrastructure.Data.xxxContext”类型的服务。

API 控制器

namespace xxx.API.Controllers
{
    [Route("api/Default")]
    [ApiController]
    public class DefaultController:ControllerBase
    {
         private ITagRepository _tagRepository;
        public DefaultController(ITagRepository tagRepository)
    {
         _tagRepository = tagRepository;
    }

    [HttpGet]
    public string GetAllUserInfo()
    {
        try
        {
            var Tags = _tagRepository.GetAllTagsByInstanceId("");
            if (Tags == null)
            {
                Tags = new List<TagEntity>();
            }
            return Tags.ToString();
        }
        catch (Exception ex)
        {
            return null;
        }
    }
}

启动.cs

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().AddControllersAsServices();
        services.AddSingleton<ModulePermissionHelper>();
        services.AddScoped<ITagRepository, TagRepository>();
        services.AddScoped<ITagModuleRepository, TagModuleRepository>();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseMvc();
    }
}

ITag 存储库

public interface ITagRepository
{
    List<TagEntity> GetAllTagsByInstanceId(string instanceId);
}

标签: c#asp.net-coredependency-injection.net-core

解决方案


根据异常消息和显示的启动,DI 容器不知道正确激活所需类型所需的依赖项。

您需要在启动期间注册 DbContext 及其相关配置

public void ConfigureServices(IServiceCollection services) {
    services.AddMvc().AddControllersAsServices();
    services.AddSingleton<ModulePermissionHelper>();
    services.AddScoped<ITagRepository, TagRepository>();
    services.AddScoped<ITagModuleRepository, TagModuleRepository>();

    //..
    services.AddDbContext<xxxContext>(options => ...);
}

文档:将 DbContext 与依赖注入一起使用


推荐阅读