0
votes

I have a solution and I have different projects in it. One of them is the api project and I want to use dependency injection in this project, but I get the following error:

Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: CCM.Business.Abstract.ICompanyService Lifetime: Scoped ImplementationType: CCM.Business.Concrete.CompanyManager': Unable to resolve service for type 'CCM.DataAccess.Concrete.CompanyDal' while attempting to activate 'CCM.Business.Concrete.CompanyManager'.)

Startup.cs:

        public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();

        services.AddScoped<ICompanyDal, CompanyDal>();

        services.AddScoped<ICompanyService, CompanyManager>();
        
        
    }

ICompanyDal:

    public interface ICompanyDal: IGenericDal<Company>
{
}

CompanyDal:

    public class CompanyDal:GenericDal<Company,CCMContext>,ICompanyDal
{
}

ICompanyService:

    public interface ICompanyService
{
    Company GetById(int id);
    List<Company> GetAll();
    void Create(Company entity);
    void Update(Company entity);
    void Delete(Company entity);
}

CompanyManager:

public class CompanyManager : ICompanyService
{
    private CompanyDal _companyDal;
    public CompanyManager(CompanyDal companyDal)
    {
        _companyDal = companyDal;
    }

    public void Create(Company entity)
    {
        _companyDal.Create(entity);
    }

    public void Delete(Company entity)
    {
        _companyDal.Delete(entity);
    }

    public List<Company> GetAll()
    {
        return _companyDal.GetAll();
    }

    public Company GetById(int id)
    {
        return _companyDal.GetById(id);
    }

    public void Update(Company entity)
    {
        _companyDal.Update(entity);
    }
}

Is there anything else I should pass on to you? please help.

2

2 Answers

0
votes

In startup, you add the service ICompanyDal with the implementation CompanyDal. But in CompanyManager, you inject the implementation CompanyDal, not the service ICompanyDal.

Solution, inject the service in the constructor :

public class CompanyManager : ICompanyService
{
    private ICompanyDal _companyDal;
    public CompanyManager(ICompanyDal companyDal)
    {
        _companyDal = companyDal;
    }
...
0
votes

Change the CompanyManager to explicitly depend on the registered abstraction

CompanyManager:

//...

private ICompanyDal _companyDal;
//CTOR
public CompanyManager(ICompanyDal companyDal) {
    _companyDal = companyDal;
}

//...

since that is what was registered with the container

Startup:

//...

services.AddScoped<ICompanyDal, CompanyDal>();

//...

Make sure that your controller(s) follow a similar format and explicitly depends on the registered abstraction(s) as well

Controller:

//...

public MyController(ICompanyService service) {
    //...
}

//...