您好,我目前正在使用MVC开发WebAPI。发出Get-Request(通过Swagger)时,将引发以下错误:
System.InvalidOperationException: Unable to resolve service for type 'Wettkampf_API_Semesterprojekt.Models.Repository.IRepository`1[Wettkampf_API_Semesterprojekt.Models.WettkampfContext]' while attempting to activate 'Wettkampf_API_Semesterprojekt.Controllers.VereinController'.
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
at lambda_method(Closure , IServiceProvider , Object[] )
at Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider.<>c__DisplayClass4_0.<CreateActivator>b__0(ControllerContext controllerContext)
at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass5_0.<CreateControllerFactory>g__CreateController|0(ControllerContext controllerContext)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
HEADERS
=======
Accept: text/plain
Accept-Encoding: gzip, deflate, br
Accept-Language: de,en-US;q=0.7,en;q=0.3
Connection: close
Cookie: Webstorm-127f7717=d590bea8-03f2-4cbb-9abb-c1d363fc6bad
Host: localhost:44325
Referer: https://localhost:44325/swagger/index.html
Te: trailers
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:76.0) Gecko/20100101 Firefox/76.0
Controller
namespace Wettkampf_API_Semesterprojekt.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class VereinController : ControllerBase
{
//Controller: Verein, PunkteKampf, GastHeim, RingerWiegeliste, Wettkampfabend, Bundesliga
private readonly IRepository<WettkampfContext> _repository;
private readonly IUnitOfWork _unitOfWork;
public VereinController(IRepository<WettkampfContext> repository, IUnitOfWork uw)
{
_repository = repository;
_unitOfWork = uw;
}
[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<IEnumerable<Verein>>> GetAsync()
{
IEnumerable<Verein> result = await _unitOfWork.Vereine.ReadAllAsync();
if (!result.Any())
{
return NotFound("There is no result for your request unfortunately. Maybe add something to the database");
}
return Ok(result);
}
[HttpPost]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<ActionResult> PostAsync([FromBody] Verein v)
{
if (v == null)
{
return BadRequest("No Input Found!");
}
await _unitOfWork.Vereine.AddAsync(v);
await _unitOfWork.CompleteAsync();
return Ok(v.Name);
}
}
}
启动
namespace Wettkampf_API_Semesterprojekt
{
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.AddDbContext<WettkampfContext>(opts => opts.UseMySql(Configuration.GetConnectionString("Wettkampf")).UseLazyLoadingProxies());
services.AddControllers();
services.AddMvc();
services.AddSwaggerGen(c => c.SwaggerDoc(name: "v1", new OpenApiInfo { Title = "Bundesliga API", Version = "v1" }));
services.AddScoped<IUnitOfWork, UnitOfWork>();
}
// 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.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseSwagger();
app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Bundesliga API V1"); });
}
}
}
工作单位类别
namespace Wettkampf_API_Semesterprojekt.Models
{
public class UnitOfWork : IUnitOfWork
{
private readonly DbContext _context;
public UnitOfWork()
{
this._context = new WettkampfContext();
Vereine = new VereinRepository(_context);
}
public IVereinRepository Vereine { get; set; }
public async Task CompleteAsync()
{
await _context.SaveChangesAsync();
}
public async ValueTask DisposeAsync()
{
await _context.DisposeAsync();
}
}
}
所有用法和接口均正确实现。似乎控制器未正确注入。我知道数量不多,但可以得到帮助。提前致谢。〜最大
让我们看一下例外:
System.InvalidOperationException:无法解析类型为'Wettkampf_API_Semesterprojekt.Models.Repository.IRepository'1 [Wettkampf_API_Semesterprojekt.Models.WettkampfContext]'的服务,而尝试激活'Wettkampf_API_Semesterproe>控制器。
因此,它无法创建
VereinController
的实例,因为它需要IRepository<WettkampfContext>
,但是没有为IRepository<WettkompfContext>
注册的服务。
您只能注入可用的服务。通常添加到Startup.cs
如果我们查看您的Startup.cs ConfigureServices()
方法,则看不到任何为IRepository添加服务的东西。您必须在此处添加它。