0

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
Qing Guo
  • 6,041
  • 1
  • 2
  • 10
Ariel
  • 1

2 Answers2

0

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>(...);

Simply Ged
  • 8,250
  • 11
  • 32
  • 40
0

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.

Qing Guo
  • 6,041
  • 1
  • 2
  • 10