How to call a custom service at startup with dependencies in dotnet core 3?

Viewed 5873

I created a dotnet core MVC app. When the app starts the first time, I want to load some data from the database to a in-memory cache.

I know how to use the IMemoryCache, to fill data inside and to get them. However, when the app start, I want to fill the in-memory cache with the data from the database. So I created a Singleton called ReferenceCache and the Interface IReferenceCache.

public interface IReferenceCache
{
    public void Setup(IMemoryCache cache);
}

public class ReferenceCache : IReferenceCache
{
    private ILogger<ReferenceCache> _logger;
    private IMemoryCache _cache;

    public void Setup(IMemoryCache cache)
    {
        //_logger = logger;
        _cache = cache;
        using (var context = new UtpmvContext())
        {
            var references = context.Reference.ToList();
            _cache.Set("reference", references);
        }
    }

    public List<Reference> GetSomeData()
    {
        var lsReferences = _cache.Get<List<Reference>>("reference");
        List<Reference> liste = lsReferences.FindAll(x => x.ReferenceId == "ANY_ID");
        return liste;
    }
}

In the ConfigureServices I added my singleton:

services.AddSingleton<IReferenceCache, ReferenceCache>();

Then in the Configure section of the startup file, I added IReferenceCache and IMemoryCache in the signature and call my setup class.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IReferenceCache cache, IMemoryCache memoryCache)
    {
        // ... code removed for clarity
        // I call my service to load the data in the in-memory 
        cache.Setup(memoryCache);
    }

The thing is in my ReferenceCache class, I want to be able to log... so how can I add a dependency of ILogger?

I have never created any service in dotnet core before so please let me know if my design is not correct.

Thank you for your help! :)

1 Answers

You could resolve the ILogger<T> using the IServiceProvider that gets passed to the AddSingleton method:

services.AddSingleton<IReferenceCache>(serviceProvider => 
    new ReferenceCache(serviceProvider.GetRequiredService<ILogger<IReferenceCache>>()));

The above registrations replaces services.AddSingleton<IReferenceCache, ReferenceCache>() in ConfigureServices.

You may resolve IMemoryCache the same as you resolve ILogger<IReferenceCache>, i.e. using the GetRequiredService method of the IServiceProvider.

This is documented here by the way.

Related