英文:
Unable to resolve service for type in .NET Core
问题
I get this error:
> Unable to resolve service for type
I am using a unit of work repository project on .NET Core. I had services in another layer, but I changed to TestServices, then I created a Services layer where there are FlightService
and IFlightService
.
Program
builder.Services.AddDbContext<DataContext>(options =>
options.UseSqlServer(builder.Configuration
.GetConnectionString("ConnectionString")));
builder.Services.AddControllers().AddJsonOptions(x =>
x.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles);
builder.Services.AddTransient<IUnitOfWork, UnitOfWork>();
builder.Services.AddScoped<IFlightRepository, FlightRepository>();
builder.Services.AddControllers();
FlightController
:
[ApiController]
[Route("Api")]
public class FlightController : Controller
{
private readonly ILogger<SearchFlightsController> _logger;
private readonly IUnitOfWork unitOfWork;
public readonly IFlightService _flightService;
public FlightController(ILogger<SearchFlightsController> logger,
IUnitOfWork unitOfWork,
IFlightService flightService)
{
_logger = logger;
this.unitOfWork = unitOfWork;
_flightService = flightService;
}
[HttpGet("GetFlightById/{flightId}")]
public async Task<IActionResult> GetFlightById(int flightId)
{
var details = await _flightService.GetFlightById(flightId);
if (details != null)
{
return Ok(details);
}
else
{
return BadRequest();
}
}
}
Error
> System.InvalidOperationException: Unable to resolve service for type 'Services.Interfaces.IFlightService' while attempting to activate 'NewShore.Controllers.FlightController'.
>
> at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
> at lambda_method4(Closure, IServiceProvider, Object[])
> at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass6_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 ---
> at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
> at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
> at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
> 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 Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
> at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
> at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)
I read some posts, I tried changing to AddScoped
both, AddTransient
for IFlightRepository
. I saw the order of the commands in Program.cs
, but everything seems ok.
Can you please correct me?
英文:
I get this error:
> Unable to resolve service for type
I am using are unit of work repository project, on .NET Core. I had a services on another layer, but I changed to TestServices, then I created a Services layer where are FlightService
and IFlightService
.
Program
builder.Services.AddDbContext<DataContext>(options =>
options.UseSqlServer(builder.Configuration
.GetConnectionString("ConnectionString")));
builder.Services.AddControllers().AddJsonOptions(x =>
x.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles);
builder.Services.AddTransient<IUnitOfWork, UnitOfWork>();
builder.Services.AddScoped<IFlightRepository, FlightRepository>();
builder.Services.AddControllers();
FlightController
:
[ApiController]
[Route("Api")]
public class FlightController : Controller
{
private readonly ILogger<SearchFlightsController> _logger;
private readonly IUnitOfWork unitOfWork;
public readonly IFlightService _flightService;
public FlightController(ILogger<SearchFlightsController> logger,
IUnitOfWork unitOfWork,
IFlightService flightService)
{
_logger = logger;
this.unitOfWork = unitOfWork;
_flightService = flightService;
}
[HttpGet("GetFlightById/{flightId}")]
public async Task<IActionResult> GetFlightById(int flightId)
{
var details = await _flightService.GetFlightById(flightId);
if (details != null)
{
return Ok(details);
}
else
{
return BadRequest();
}
}
}
Error
> System.InvalidOperationException: Unable to resolve service for type 'Services.Interfaces.IFlightService' while attempting to activate 'NewShore.Controllers.FlightController'.
>
> at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
> at lambda_method4(Closure, IServiceProvider, Object[])
> at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass6_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 ---
> at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
> at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
> at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
> 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 Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
> at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
> at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)
I read some posts, I tried changing to AddScoped
both, AddTransient
for IFlightRepository
. I saw the order or the commands on Program.cs
but everything seems ok.
Can you please correct me?
答案1
得分: 5
You injected IFlightService into FlightController, but not registered this dependency. Error message tells you that dependency in FlightController cannot be resolved.
Add this line to Program.cs
builder.Services.AddTransient<IFlightService, FligtService>();
英文:
You injected IFlightService into FlightController, but not registered this dependency. Error message tells you that dependency in FlightController cannot be resolved.
Add this line to Program.cs
builder.Services.AddTransient<IFlightService, FligtService>();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论