1

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.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.g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.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?

3
  • Please post the error message including Stacktrace. Commented Apr 19, 2023 at 6:55
  • Error information added. Commented Apr 19, 2023 at 7:11
  • You add IFlightRepository but not IFlightService that is used in your controller. And that's what the error is telling you : the app doesn't know about IFlightService that you want to use in your controller, as you didn't add the service in your startup EDIT : @riktus was faster than me :). Check his answer Commented Apr 19, 2023 at 7:23

1 Answer 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>();
Sign up to request clarification or add additional context in comments.

1 Comment

FightService and FlightRepository... they look similar, thanks guys.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.