[Solved] ASP.Net Core Autofac Error: InvalidOperationException: Unable to resolve service for type

AliYilmaz
 
on May 31, 2022 02:04 AM
3175 Views

Hi,

I'm trying to include Autofac in my .NET Core project. But it doesn't see my repositories. What is the problem here? How will I find the solution?

I have repository pattern in my project. That's why I'm getting an error. What should I do in this situation? Is there such an example? 

Error : "InvalidOperationException: Unable to resolve service for type IBeyannameReadRepository"

public class AutofacBusinessModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterType<BeyannameReadRepository>().As<IBeyannameReadRepository>();
        builder.RegisterType<BeyannameWriteRepository>().As<IBeyannameWriteRepository>();
        builder.RegisterInstance(AutoMapperConfig.Initialize()).SingleInstance();
    }
}

Startup.cs

public class Startup
{
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddRazorPages();
        services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
    }       
 
    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
 
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseRouting();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}");
        });
    }
}

Program.cs

public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .UseServiceProviderFactory(new AutofacServiceProviderFactory())
        .ConfigureContainer<ContainerBuilder>(builder=> {
           builder.RegisterModule(new AutofacBusinessModule());
        })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download