Home > database >  ASP.NET Core 6 Dependency injection in controller return System.InvalidOperationException: Unable to
ASP.NET Core 6 Dependency injection in controller return System.InvalidOperationException: Unable to

Time:03-29

I'm trying to develop a Web API project with ASP.NET Core 6, but I get this error, there seems to be an error in the dependency injection, but I haven't found this:

System.InvalidOperationException: Unable to resolve service for type 'api.Interface.IUsersService' while attempting to activate 'api.Controllers.UsersController'.

at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
at lambda_method3(Closure , IServiceProvider , Object[] )
at Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider.<>c__DisplayClass7_0.b__0(ControllerContext controllerContext)
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.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Startup.cs :

public void ConfigureServices(IServiceCollection services)
{
       string connectionString = Configuration.GetConnectionString("DefaultConnection");
       services.AddDbContext<DataContext>(options => options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString)));
       services.AddCors(options => options.AddPolicy("ApiCorsPolicy", build =>
        {
            build.WithOrigins("http://localhost:8080")
                 .AllowAnyMethod()
                 .AllowAnyHeader();
        }));
        services.AddMvc();
        services.AddControllers();
        services.AddScoped<IJwtUtils, JwtUtils>();
        services.AddScoped<IUsersService, UsersService>();
        services.AddScoped<IQrcodesService, QrcodesService>();
        services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
        services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

        services.AddControllers().AddJsonOptions(options =>
        {
            options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
        });
}

IUsersService.cs:

using api.Response;
using System.Collections.Generic;

namespace api.Interface
{
    public interface IUsersService
    {
        // ...
    }
}

UsersService.cs:

using api.Authorization;
using api.Helpers;
using api.Interface;
using api.Response;
using AutoMapper;
using System.Collections.Generic;
using System.Linq;
using BCryptNet = BCrypt.Net.BCrypt;

namespace api.Services
{
    public class UsersService : IUsersService
    {
        private DataContext _context;
        private IJwtUtils _jwtUtils;
        private readonly IMapper _mapper;

        public UsersService(
            DataContext context,
            IJwtUtils jwtUtils,
            IMapper mapper)
        {
            _context = context;
            _jwtUtils = jwtUtils;
            _mapper = mapper;
        }

        // ...
    }
}

UsersController.cs:

using api.Helpers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using api.Response;
using api.Authorization;
using api.Interface;

namespace api.Controllers
{
    [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class UsersController : ControllerBase
    {
        private readonly IUsersService _userService;
        private readonly AppSettings _appSettings;

        public UsersController(
            IUsersService userService,
            IOptions<AppSettings> appSettings)
        {
            _userService = userService;
            _appSettings = appSettings.Value;
        }

        // ...
    }
}

DataContext.cs:

using System;
using Microsoft.EntityFrameworkCore;
using api.Response;
using BCryptNet = BCrypt.Net.BCrypt;
using api.Authorization;

namespace api.Helpers
{
    public class DataContext : DbContext
    {
        public DataContext() { }

        public DataContext(DbContextOptions<DataContext> options) : base(options) { }

        public DbSet<User> Users { get; set; }
        public DbSet<Role> Roles { get; set; }
        public DbSet<QRcode> QRcodes { get; set; }
        public DbSet<Activity> Activities { get; set; }
        public DbSet<Giustification> Giustifications  { get; set; }
       
        // ...
    }
}

JwtUtils.js:

public class JwtUtils : IJwtUtils
{
    private readonly AppSettings _appSettings;

    public JwtUtils(IOptions<AppSettings> appSettings)
    {
        _appSettings = appSettings.Value;
    }
           //...
}

I'm using pomelo 6.0.1 with mysql '8.0.27' and .NET 6.

CodePudding user response:

I think this services.Configure(Configuration.GetSection("AppSettings")); line need to be executed before services.AddScoped<IJwtUtils, JwtUtils>();

CodePudding user response:

I found the solution, the project started with .net 5 and then migrated to 6. The new version has changed file Program.cs

My new Program.cs

using api;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Hosting;

var builder = WebApplication.CreateBuilder(args);

var startup = new Startup(builder.Configuration);


startup.ConfigureServices(builder.Services);

var app = builder.Build();

startup.Configure(app, app.Environment);

app.Run();

for more information on how to migrate the project : Migrate from ASP.NET Core 5.0 to 6.0 I want to thank everyone for the answers.

  • Related