InvalidOperationException: Unable to resolve service for type "" while attempting to activate dotnet core 7

458 Views Asked by At

I try add

using SciEn.Repo.Contracts;
using SciEn.Repo.IRepository;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.


builder.Services.AddSingleton<ISubDepartmentRepository, SubDepartmentRepository>();



var app = builder.Build();

I got this error

'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: SciEn.Repo.Contracts.ISubDepartmentRepository Lifetime: Scoped ImplementationType: SciEn.Repo.IRepository.SubDepartmentRepository': Unable to resolve service for type 'SciEn.Models.ScinceContext' while attempting to activate 'SciEn.Repo.IRepository.SubDepartmentRepository'.)'

I try remove

builder.Services.AddScoped<ISubDepartmentRepository, SubDepartmentRepository>();

but get error

InvalidOperationException: Unable to resolve service for type "" while attempting to activate
2

There are 2 best solutions below

0
Simply Ged On

Unable to resolve service for type 'SciEn.Models.ScinceContext' while attempting to activate 'SciEn.Repo.IRepository.SubDepartmentRepository'.)

This error is telling you that when it tried to create the SubDepartmentRepository class it couldn't find the ScinceContext that needs to be injected into it's constructor.

You need to ensure you have registered the SciEn.Models.ScinceContext class. Is this an Entity Framework DB Context? Make sure you've registered the DB Context...

builder.Services.AddDbContext<SciEn.models.ScinceContext>(...);

0
Qing Guo On

There are two things you need to care:

1.Create an instance of ScinceContext to pass into the SubDepartmentRepository.

2.Since DbContext is scoped by default, you need to create scope to access it.

Please check with your code something like below:

builder.Services.AddDbContext<ScinceContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("Connectionstring")));

builder.Services.AddScoped<ISubDepartmentRepository, SubDepartmentRepository>();

If you really need to use a dbContext inside a singleton, you can read this to know more.