Kelly Soares

Kelly Soares

  • NA
  • 43
  • 11.4k

Unable to cast object of type Microsoft.Extensions.DependencyInjection

Aug 7 2022 9:49 PM

Hi,

I'm trying to implement dependency injection in my project, but when executing it, the following error appears on the line where I register my AddInfraEstructure service:

System.InvalidCastException: 'Unable to cast object of type 'Microsoft.Extensions.DependencyInjection.ServiceCollection' to type 'System.IServiceProvider'.'

How do I do this type of conversion?

Code:

    public static class DependencyInjection
    {
        public static IServiceProvider AddInfraEstructure(this IServiceCollection services,
            IConfiguration configuration)
        {
            services.AddDbContext<AppDbContext>(options =>
            options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")));

            services.AddScoped<IEstadoRepository, EstadoRepository>();
            services.AddScoped<IUnidadeFederativaService, EstadoService>();

            return services;
        }
    }

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Project.Infra.IoC;
using Project.MVC.MappingConfig;

namespace Project.MVC
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddInfraEstructure(Configuration);
            services.AddAutoMapperConfiguration();
            services.AddControllersWithViews();
            services.AddRazorPages();
        }

    }
}


Answers (5)