Search code examples
c#.net-corecachingdependency-injection.net-6.0

c# on application start get data from database and cache it


I am trying in my ASP.NET Core 6 MVC web application, on start, to get data from the database and cache it.

I've been around this for two days, and I couldn't figure out how to do it, but here is what I've try and failed and didn't understand the error.

I tried to write a class inheriting from IStartupFilter with this code:

public class RequestSetOptionsMiddleware
{
    private readonly RequestDelegate _next;
    private readonly IServiceProvider _provider;

    public RequestSetOptionsMiddleware(RequestDelegate next, IServiceProvider provider)
    {
        _next = next;
        _provider = provider;
    }

    // Test with https://localhost:5001/Privacy/?option=Hello
    public async Task Invoke(HttpContext httpContext)
    {
        Console.WriteLine("test 12312 1 23 123 1 23 12");
        
        var cont = _provider.GetService<IAccountManagerRepository>();
        var asdasd = cont.GetAccountManagersThirdPartyNotTrueWithSelection();

        await _next(httpContext);
    }
}

public class RequestSetOptionsStartupFilter : IStartupFilter
{
    public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next)
    {
        return builder =>
        {
            builder.UseMiddleware<RequestSetOptionsMiddleware>();
            next(builder);
        };
    }
}

And in the program class I have:

builder.Services.AddTransient<IStartupFilter, RequestSetOptionsStartupFilter>();

I got this error:

enter image description here

You can see - I can't inject my repository interface.

Thanks in advance


Solution

  • The problem is that you are trying to resolve a Scoped service from the root provider.

    A new scope is created with every request, so you must resolve the service from the scoped provider that is in the HttpContext. To do this you need to change the _provider.GetService() line in your RequestSetOptionsMiddleware middleware to :

    var cont = httpContext.RequestServices.GetService<IAccountManagerRepository>();