Skip to content

Injection into custom RazorPage? #25

Description

@Bouke

I'm using a custom RazorPage<TModel> which I'd like to have dependencies injected into. It needs a parameterless constructor for MVC, meaning I have to use property injection.

# MyRazorPage.cs
public abstract class MyRazorPage<TModel> : RazorPage<TModel>
{
    [Import]
    public ITenantContextProvider<TenantContext> tenantProvider { get; init; }

    public TenantContext? Tenant => tenantProvider.GetContext();
}
#_ViewImports.cshtml
@inherits MyRazorPage<TModel>

I'm assuming IPropertySelectionBehavior and IComponentActivator would work here as well, but it doesn't. The property remains null. Furthermore if I use RazorInject I'm getting an exception from Microsoft DI that ITenantContextProvider<TenantContext> is not a registered service:

System.InvalidOperationException: No service for type 'ITenantContextProvider`1[TenantContext]' has been registered.
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.AspNetCore.Mvc.Razor.RazorPagePropertyActivator.<>c__DisplayClass8_0.<CreateActivateInfo>b__1(ViewContext context)
   at Microsoft.Extensions.Internal.PropertyActivator`1.Activate(Object instance, TContext context)
   at Microsoft.AspNetCore.Mvc.Razor.RazorPagePropertyActivator.Activate(Object page, ViewContext context)
   at Microsoft.AspNetCore.Mvc.Razor.RazorPageActivator.Activate(IRazorPage page, ViewContext context)

(split from simpleinjector/SimpleInjector#860 (comment))

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions