我收到以下错误。我正在使用.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;
}
}
}
Startup.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();
}
}
ITagRepository
public interface ITagRepository
{
List<TagEntity> GetAllTagsByInstanceId(string instanceId);
}
答案 0 :(得分:0)
基于异常消息和所示的启动,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 => ...);
}