Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

.NET 6.0 DI Service Registration Issue

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading