TypeFilterAttribute

目录

1 TypeFilterAttribute

1.1 /// Gets or sets the order in which the action filters are executed.

1.2 /// Gets or sets the non-service arguments to pass to the constructor.

1.3 /// Service arguments are found in the dependency injection container i.e. this filter supports constructor

  1. TypeFilterAttribute

using System;

using System.Diagnostics;

using System.Linq;

using Microsoft.Extensions.DependencyInjection;

namespace Flatwhite.Core

{

/// 

/// https://github.com/aspnet/Mvc/blob/65af12f1f575fdaee893e0232416df29bb83d7fa/src/Microsoft.AspNetCore.Mvc.Core/TypeFilterAttribute.cs

/// 

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]

    [DebuggerDisplay("TypeFilter: Type={ImplementationType} Order={Order}")]

    public class TypeFilterAttribute : Attribute, IFilterFactory

    {

    /// 

    1.     /// Gets or sets the order in which the action filters are executed.

    /// 

    public int Order { get; set; }

        private ObjectFactory _factory;

        /// 

        /// Instantiates a new TypeFilterAttribute"/> instance.

        /// 

        /// type">The Type"/> of filter to create.

        public TypeFilterAttribute(Type type)

        {

ImplementationType = type ?? throw new ArgumentNullException(nameof(type));

        }

        /// 

    1.         /// Gets or sets the non-service arguments to pass to the ImplementationType"/> constructor.

        /// 

        /// 

    1.         /// Service arguments are found in the dependency injection container i.e. this filter supports constructor

        /// injection in addition to passing the given Arguments"/>.

        /// 

        public object[] Arguments { get; set; }

        /// 

        /// Gets the Type"/> of filter to create.

        /// 

        public Type ImplementationType { get; }

        

        /// 

/// IFilterFactory"/>

/// 

/// serviceProvider">

/// 

        public MethodFilterAttribute CreateInstance(IServiceProvider serviceProvider)

        {

            if (serviceProvider == null)

            {

                throw new ArgumentNullException(nameof(serviceProvider));

            }

            if (_factory == null)

            {

                var argumentTypes = Arguments?.Select(a => a.GetType())?.ToArray();

                _factory = ActivatorUtilities.CreateFactory(ImplementationType, argumentTypes ?? Type.EmptyTypes);

            }

            var filter = (MethodFilterAttribute)_factory(serviceProvider, Arguments);

            if (filter is IFilterFactory filterFactory)

            {

                // Unwrap filter factories

                filter = filterFactory.CreateInstance(serviceProvider);

            }

filter.Order = Order;

            return filter;

        }

    }

}

你可能感兴趣的:(Flatwhite,开发语言)