c# - 尝试激活 '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);
}
解决方案
根据异常消息和显示的启动,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 => ...);
}
推荐阅读
- android - 评分栏在 android 中有 10 颗星
- npm - npm run scripts 运行无限时间
- javascript - × TypeError: Object(...) 不是函数
- javascript - Sanic Websocket 异步管理
- reactjs - 在设备视图之外反应原生模态内容
- django - Gunicorn 没有开始抛出 gunicorn.service:失败,结果为“退出代码”。错误
- python - 无法获得正确的元组格式的元组以传递给 Python 中的 for 循环迭代
- bash - “-”在 bash 中有什么作用(例如 sort -)
- java - 如何在 Java 中转发异常对象
- c# - 指定(或未指定)键时的模板加载行为不同