Unable to resolve service for type in .NET Core

huangapple go评论74阅读模式
英文:

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&lt;DataContext&gt;(options =&gt;
    options.UseSqlServer(builder.Configuration
    .GetConnectionString(&quot;ConnectionString&quot;)));

builder.Services.AddControllers().AddJsonOptions(x =&gt;
                x.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles);

builder.Services.AddTransient&lt;IUnitOfWork, UnitOfWork&gt;();

builder.Services.AddScoped&lt;IFlightRepository, FlightRepository&gt;();

builder.Services.AddControllers();

FlightController:

[ApiController]
[Route(&quot;Api&quot;)]
public class FlightController : Controller
{
        private readonly ILogger&lt;SearchFlightsController&gt; _logger;        
        private readonly IUnitOfWork unitOfWork;
        public readonly IFlightService _flightService;

        public FlightController(ILogger&lt;SearchFlightsController&gt; logger,
            IUnitOfWork unitOfWork,
            IFlightService flightService)
        {
            _logger = logger;            
            this.unitOfWork = unitOfWork;
            _flightService = flightService;
        }

        [HttpGet(&quot;GetFlightById/{flightId}&quot;)]
        public async Task&lt;IActionResult&gt; 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&lt;IFlightService, FligtService&gt;();

huangapple
  • 本文由 发表于 2023年4月19日 14:47:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76051479.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定