dimanche 1 octobre 2023

Injecting DbContext and Repository into class library service constructor

I'm getting an error using DI in a service located in a different class library to my main blazor application.

System.InvalidOperationException: No service for type 'Services.SomeService' has been registered. 

This is what the Service looks like currently (it resides in it's own class library):

public class SomeService : ISomeService
{
    
    private IDbContextFactory<ApplicationDbContext> DbContextFactory { get; set; }
    private IGPSFixRepository GpsFixRepository { get; set; } = default!;
    
    public SomeService(IDbContextFactory<ApplicationDbContext> contextSQLDb, IGPSFixRepository gpsFixRepository)
    {
        DbContextFactory = contextSQLDb;
        this.GpsFixRepository = gpsFixRepository;
    }
    
}

The constructor for the GPSFixRepository requires a context factory:

public GPSFixRepository(IDbContextFactory<ApplicationDbContext> contextSQLDb)

I have declared the services in the client Program.cs:

builder.Services.AddDbContextFactory<ApplicationDbContext>(options =>
    options.UseSqlServer(connectionStringIdentity));
builder.Services.AddScoped<ISomeService, SomeService>();

I'm assuming that the DI is not able to create an instance of the IGPSFixRepository since it requires the context factory in it's constructor.

How do I inform the DI such that it creates a context factory when creating the IGPSFixRepository?

Aucun commentaire:

Enregistrer un commentaire