rcs
rcs

Reputation: 7197

C# Dependency Injection : Injecting multiple interfaces into other services

I'd like to inject a number of interfaces to another service. Let's take a look at 2 services that I want to have their dependency injected.

Inside Term.cs

private readonly IWSConfig WSConfig;
private readonly IMemoryCache MemCache;

public Term(IWSConfig wsConfig, IMemoryCache memoryCache)
{
    WSConfig = wsConfig;
    MemCache = memoryCache;
}


public async Task LoadData()
{
    List<ConfigTerm> configTerm = await WSConfig.GetData(); // This is a web service call
    ...
}

Inside Person.cs

private readonly PersonRepo PersonRepository;
private readonly IMemoryCache MemCache;
private readonly ITerm Term;
private readonly IWSLoadLeave LoadLeave;
private readonly IWSLoadPartics LoadPartics;

public Person(PersonRepo personRepository, IMemoryCache memCache, ITerm term, IWSLoadLeave loadLeave, IWSLoadPartics loadPartics)
{
    PersonRepository = personRepository;
    MemCache = memCache;
    Term = term;
    LoadLeave = loadLeave;
    LoadPartics = loadPartics;
}

Code in Startup.cs

services.AddDbContext<DBContext>(opts => opts.UseOracle(RegistryReader.GetRegistryValue(RegHive.HKEY_LOCAL_MACHINE, Configuration["AppSettings:RegPath"], "DB.ConnectionString", RegWindowsBit.Win64)));
services.AddTransient<ILogging<ServiceLog>, ServiceLogRepo>();
services.AddSingleton<IMemoryCache, MemoryCache>();    
services.AddHttpClient<IWSConfig, WSConfig>();
services.AddHttpClient<IWSLoadLeave, WSLoadLeave>();
services.AddHttpClient<IWSLoadPartics, WSLoadPartics>();

var optionsBuilder = new DbContextOptionsBuilder<DBContext>(); // Can we omit this one and just use the one in AddDbContext?
optionsBuilder.UseOracle(RegistryReader.GetRegistryValue(RegHive.HKEY_LOCAL_MACHINE, Configuration["AppSettings:RegPath"], "DB.ConnectionString", RegWindowsBit.Win64));

services.AddSingleton<ITerm, Term>((ctx) => {
    WSConfig wsConfig = new WSConfig(new System.Net.Http.HttpClient(), new ServiceLogRepo(new DBContext(optionsBuilder.Options))); // Can we change this to the IWSConfig and the ILogging<ServiceLog>
    IMemoryCache memoryCache = ctx.GetService<IMemoryCache>();
    return new Term(wsConfig, memoryCache);
});
services.AddSingleton<IPerson, Person>((ctx) => {
    PersonRepo personRepo = new PersonRepo(new DBContext(optionsBuilder.Options)); // Can we change this?
    IMemoryCache memoryCache = ctx.GetService<IMemoryCache>();
    ITerm term = ctx.GetService<ITerm>();
    WSLoadLeave loadLeave = new WSLoadLeave(new System.Net.Http.HttpClient(), new ServiceLogRepo(new DBContext(optionsBuilder.Options))); // Can we change this?
    WSLoadPartics loadPartics = new WSLoadPartics(new System.Net.Http.HttpClient(), new ServiceLogRepo(new DBContext(optionsBuilder.Options))); // Can we change this?
    return new Person(personRepo, memoryCache, term, loadLeave, loadPartics);
});

But there are some duplication here and there. I've marked as the comments in the code above. How to correct it ?

[UPDATE 1]: If I change the declaration from singleton with the following:

services.AddScoped<ITerm, Term>();
services.AddScoped<IPerson, Person>();

I'm getting the following error when trying to insert a record using the DbContext.

{System.ObjectDisposedException: Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances. Object name: 'DBContext'.

In my WSConfig, it will inherit a base class. This base class also have reference to the ServiceLogRepo, which will call the DbContext to insert a record to the database

In WSConfig

public class WSConfig : WSBase, IWSConfig
{
    private HttpClient WSHttpClient;

    public WSConfig(HttpClient httpClient, ILogging<ServiceLog> serviceLog) : base(serviceLog)
    {
        WSHttpClient = httpClient;

        //...
    }

    //...
}

The WSBase class:

public class WSBase : WSCall
{    
    private readonly ILogging<ServiceLog> ServiceLog;

    public WSBase(ILogging<ServiceLog> serviceLog) : base(serviceLog)
    {

    }

    ...
}

The WSCall class:

public class WSCall 
{
    private readonly ILogging<ServiceLog> ServiceLog;

    public WSCall(ILogging<ServiceLog> serviceLog)
    {
        ServiceLog = serviceLog;
    }
    ....
}

And the ServiceLogRepo code

public class ServiceLogRepo : ILogging<ServiceLog>
{
    private readonly DBContext _context;

    public ServiceLogRepo(DBContext context)
    {
        _context = context;
    }

    public async Task<bool> LogRequest(ServiceLog apiLogItem)
    {
        await _context.ServiceLogs.AddAsync(apiLogItem);
        int i = await _context.SaveChangesAsync();

        return await Task.Run(() => true);
    }
}

I also have the following in Startup.cs to do the web service call upon application load.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ITerm term)
{
    ....
    System.Threading.Tasks.Task.Run(async () => await term.LoadData());
}

It seems when going into term.LoadData(), the DBContext is disposed already.

Upvotes: 0

Views: 1528

Answers (1)

Nkosi
Nkosi

Reputation: 247098

First properly register all the necessary dependencies in ConfigureServices using the appropriate liftetime scopes

services.AddDbContext<DBContext>(opts => opts.UseOracle(RegistryReader.GetRegistryValue(RegHive.HKEY_LOCAL_MACHINE, Configuration["AppSettings:RegPath"], "DB.ConnectionString", RegWindowsBit.Win64)));
services.AddTransient<ILogging<ServiceLog>, ServiceLogRepo>();
services.AddSingleton<IMemoryCache, MemoryCache>();    
services.AddHttpClient<IWSConfig, WSConfig>();
services.AddHttpClient<IWSLoadLeave, WSLoadLeave>();
services.AddHttpClient<IWSLoadPartics, WSLoadPartics>();

services.AddScoped<ITerm, Term>();
services.AddScoped<IPerson, Person>();

Given the async nature of the method being called in Configure the DbContext is being disposed before you are done with it.

Now ideally given what you are trying to achieve you should be using a background service IHostedServive which will be started upon startup of the application.

public class TermHostedService : BackgroundService {
    private readonly ILogger<TermHostedService> _logger;

    public TermHostedService(IServiceProvider services, 
        ILogger<ConsumeScopedServiceHostedService> logger) {
        Services = services;
        _logger = logger;
    }

    public IServiceProvider Services { get; }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
        _logger.LogInformation("Term Hosted Service running.");

        using (var scope = Services.CreateScope()) {
            var term = scope.ServiceProvider.GetRequiredService<ITerm>();    
            await term.LoadData();
            _logger.LogInformation("Data Loaded.");
        }
    }

    public override async Task StopAsync(CancellationToken stoppingToken) {
        _logger.LogInformation("Term Hosted Service is stopping.");    
        await Task.CompletedTask;
    }
}

when registered at startup

services.AddHostedService<TermHostedService>();

Reference Background tasks with hosted services in ASP.NET Core

Upvotes: 1

Related Questions