user807722
user807722

Reputation: 51

Configuring ASP.NET Core razor page filter using model.Filters.Add<TFilterType>()

I can setup an ASP.NET Core razor page filter in startup that has dependency injection just fine using <<TType>>() rather than new Type():

services.AddMvc(options =>
{
    options.Filters.Add<Filters.AdminPageFilter>();
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddHttpContextAccessor();

This works fine, but would like to apply this to a directory doing something like:

services.AddMvc().AddRazorPagesOptions(options =>
{
    options.Conventions.AddFolderApplicationModelConvention(
        "/Admin",
        model => model.Filters.Add<Filters.AdminPageFilter>()
        );
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

Compilation complains:

Error CS7036 There is no argument given that corresponds to the required formal parameter 'configureSource' of 'ConfigurationExtensions.Add(IConfigurationBuilder, Action)' Startup.cs 71 Active

Is there a way to Just specify the type via model.Filters.Add<Filters.AdminPageFilter>() and not create an new Instance via model.Filters.Add(new Filters.AdminPageFilter())?

Upvotes: 3

Views: 893

Answers (1)

Ber&#39;Zophus
Ber&#39;Zophus

Reputation: 7687

TypeFilterAttribute can help with this. It operates as a filter factory that can generate your filter using dependency injection. It implements IFilterMetadata, so it can be added to model.Filters in the place of your AdminPageFilter.

Here's an extension method that will give you the same .Add<FilterType> functionality:

using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

public static void Add<TFilterType>(this ICollection<IFilterMetadata> filters) where TFilterType : IFilterMetadata {
    var typeFilterAttribute = new TypeFilterAttribute(typeof(TFilterType));
    filters.Add(typeFilterAttribute);
}

Upvotes: 1

Related Questions