Home > OS >  .NET 6.0 DI Service Registration Issue
.NET 6.0 DI Service Registration Issue

Time:09-07

I am using a repository pattern and trying to register services in .NET 6.0 using DI.

In Program.cs,

builder.Services.AddSingleton<DapperContext>();
builder.Services.AddSingleton<IDomain, Domain>();
builder.Services.AddScoped<IApiUserRepository, ApiUserRepository>();

ApiUserRepository.cs

public class ApiUserRepository : IApiUserRepository
{
    private readonly DapperContext _context;
    private readonly Domain _domain;

    public ApiUserRepository(DapperContext context, Domain domain)
    {
        _context = context;
        _domain = domain;
    }
}

Domain.cs

public class Domain : IDomain
{
    private IConfiguration _configuration;
    public Domain(IConfiguration configuration)
    {
        _configuration = configuration;
    }
    public string GetDomainNameFromConfiguration()
    {
        return _configuration.GetValue<string>("Domain");
    }
}

I am getting the following exception,

System.AggregateException: 'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: RepositoryContracts.IApiUserRepository Lifetime: Scoped ImplementationType: Repositories.ApiUserRepository': Unable to resolve service for type 'Repositories.Domain' while attempting to activate 'Repositories.ApiUserRepository'.)'

Inner exception,

InvalidOperationException: Unable to resolve service for type 'Repositories.Domain' while attempting to activate 'Repositories.ApiUserRepository'.

CodePudding user response:

You should change the constructor of ApiUserRepository to inject IDomain in stead of Domain

Domain is registered only as IDomain, so Domain itself cannot be resolved.

Alternatively you can register the Domain class.

  • Related