Open kekefigure opened 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();
}
}
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.
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?