HangfireIO / Hangfire

An easy way to perform background job processing in .NET and .NET Core applications. No Windows Service or separate process required
https://www.hangfire.io
Other
9.33k stars 1.69k forks source link

Access ServiceProvider of requests in AddRazorPage #1530

Open kekefigure opened 4 years ago

kekefigure commented 4 years ago

If a RazorPage has dependencies which could be resolved from the DI container, it would be nice to access the current requests ServiceProvider. Is there a way to access this from AddRazorPage method?

pieceofsummer commented 4 years ago

Not with the current AddRazorPage overload, because it knows nothing about DI whatsoever. Making it DI-aware would introduce dependency to a DI framework.

But you can still get HttpContext (and its RequestServices) from the page code and resolve required services. You'll need a bit of reflection though, because RazorPage's Context property is internal:

public static class RazorPageExtensions
{
    private static readonly PropertyInfo ContextProp =
        typeof(RazorPage).GetTypeInfo().GetDeclaredProperty("Context");

    public static HttpContext GetHttpContext(this RazorPage page)
    {
        if (page == null) throw new ArgumentNullException("page")
        var context = (DashboardContext) ContextProp.GetValue(page);
        return context?.GetHttpContext();
    }
}
kekefigure commented 4 years ago

I'd like to keep the page code clean as possible, so resolving dependencies, loading data should happen before the page is created.

Accessing the DashboardContext in AddRazorPage would be great, dependencies could be resolved with DashboardContext .GetHttpContext().RequestServices. It wouldn't introduce any new dependency. Request query values would be accessible through DashboardContext .Request.GetQuery() method which helps in implementing custom pages with paging.

Commands also have access to the DashboardContext, so it would be more consistent with the other extensions.