The ASP.NET Core ActionFilter and DI

I. Introduction

  The previous articles are talking about dependency injection (DI) ASP.NET Core MVC in the extension point, maybe we have found in ASP.NET CORE All components are through dependency injection to expand, but for a group of there will be a function of a set of interfaces or abstract factory to extend the functionality, as IControllerActivator function point on this article (see the source code for .NET Core reliance by Autofac injected into the Controller property) are also mentioned, today we introduce a similar large extension points, ASP.NET Core MVC provides a new mechanism for the expansion of our dependency injection to Action filters (ie filters).

Second, the filter dependency injection

  In ASP.NET Core MVC, the framework provides us with the type  IFilter  the Attributes to decorate Action, Action for intercepting the request, which had in previous versions, but if we want to combine, then to use dependency injection use IFilterFactory interface to extend the process of creating the Action Filter.

  2.1  IFilterFactory interface definition

public interface IFilterFactory : IFilter
{
    IFilter CreateInstance([NotNull] IServiceProvider serviceProvider);
}

 

  Code that we want and need to create a Filter Attribute dependency injection, then generally you want to:

Copy the code
public class FilterClass: ActionFilterAttribute   
{ 
  public FilterClass (IDependency1 dependency1, IDependency2 dependency2) 
  { 
    // ... use dependencies 
  } 
}
Copy the code

 

  ASP.NET Core MVC provides two simple for us IFilterFactory ServiceFilterAttribute  and  TypeFilterAttribute  . Be an example to see how to use.

Copy the code
public class HomeController: Controller  
{
    [TypeFilter(typeof(FilterClass))]
    [ServiceFilter(typeof(FilterClass))]
    public IActionResult Index()
    {
        return View();
    }
}
Copy the code

  2.2 ServiceFilterAttribute 

   Actually see the name, some friends will be able to think, and it is based on dependency injection of a IFilterFactory , Service reinforces this word it is a dependency injection to achieve by getting services, we think of what? Is not GetService ()? Yes, in fact, it is this mechanism.

     To ServiceFilter registered on the type of container to be injected corresponding to rely, as in the following example, we must first register to the IOC FilterClass type container.

public void ConfigureServices(IServiceCollection services)
{
      services.AddSingleton<FilterClass>();
 
      services.AddMvc()
}

  Of course, if the type of construction requires FilterClass injection type, but also need to register IOC container can be used.

  ServiceFilterAttribute we look at the source code:

Copy the code
public class ServiceFilterAttribute : Attribute, IFilterFactory, IOrderedFilter
{
    public ServiceFilterAttribute([NotNull] Type type)
    {
        ServiceType = type;
    }

    public Type ServiceType { get; private set; }

    public int Order { get; set; }

    public IFilter CreateInstance([NotNull] IServiceProvider serviceProvider)
    {
        var service = serviceProvider.GetRequiredService(ServiceType);

        var filter = service as IFilter;
        if (filter == null)
        {
            throw new InvalidOperationException(Resources.FormatFilterFactoryAttribute_TypeMustImplementIFilter(
                typeof(ServiceFilterAttribute).Name,
                typeof(IFilter).Name));
        }

        return filter;
    }
}
Copy the code

  2.3  Type Filtering guest tribute

   Of course you can also choose to use this filter similar ServiceFilter TypeFilter filter, it also implements IFilterFactory interfaces, and can be used to create the dependency injection to filter through it. TypeFilter was called because it does not need to register the type of container can create a filter in dependency injection, we look at its code:

Copy the code
public class TypeFilterAttribute : Attribute, IFilterFactory, IOrderedFilter
{
    private ObjectFactory factory;

    public TypeFilterAttribute([NotNull] Type type)
    {
        ImplementationType = type;
    }

    public object[] Arguments { get; set; }

    public Type ImplementationType { get; private set; }

    public int Order { get; set; }

    public IFilter CreateInstance([NotNull] IServiceProvider serviceProvider)
    {
        if (this.factory == null)
        {
            var argumentTypes = Arguments?.Select(a => a.GetType())?.ToArray();

            this.factory = ActivatorUtilities.CreateFactory(ImplementationType, argumentTypes ?? Type.EmptyTypes);
        }

        return (IFilter)this.factory(serviceProvider, Arguments);
    }
}
Copy the code

Third, the conclusion

  Who saw an article on the friends I have noticed ServiceProvider and ActivatorUtilities  different on this article ServiceFilterAttribute and TypeFilterAttribute principle is to create a Filter by them, so the use of scenarios to see how everyone to use. In fact, I recently .NET Core source code, you can see everywhere interfaces, factory use dependency injection example of forming the extension point, in fact, Microsoft's previous extension points also with a lot of code, but not so open API, ASP.NET Core we see an "open" framework.

 

  GitHub: https://github.com/maxzhang1985/YOYOFx   if sleep also can ask Star , the welcome exchange.

 

  .NET Core open source learning group:  214 741 894  

 

 
 
6
0
 
 
 
<<  Previous:  View .NET Core source dependency injection to achieve by the Controller property Autofac
>>  Next Article:  solve ASP.NET Core Mvc file upload limit problem

I. Introduction

  The previous articles are talking about dependency injection (DI) ASP.NET Core MVC in the extension point, maybe we have found in ASP.NET CORE All components are through dependency injection to expand, but for a group of there will be a function of a set of interfaces or abstract factory to extend the functionality, as IControllerActivator function point on this article (see the source code for .NET Core reliance by Autofac injected into the Controller property) are also mentioned, today we introduce a similar large extension points, ASP.NET Core MVC provides a new mechanism for the expansion of our dependency injection to Action filters (ie filters).

Second, the filter dependency injection

  In ASP.NET Core MVC, the framework provides us with the type  IFilter  the Attributes to decorate Action, Action for intercepting the request, which had in previous versions, but if we want to combine, then to use dependency injection use IFilterFactory interface to extend the process of creating the Action Filter.

  2.1  IFilterFactory interface definition

public interface IFilterFactory : IFilter
{
    IFilter CreateInstance([NotNull] IServiceProvider serviceProvider);
}

 

  Code that we want and need to create a Filter Attribute dependency injection, then generally you want to:

Copy the code
public class FilterClass: ActionFilterAttribute   
{ 
  public FilterClass (IDependency1 dependency1, IDependency2 dependency2) 
  { 
    // ... use dependencies 
  } 
}
Copy the code

 

  ASP.NET Core MVC provides two simple for us IFilterFactory ServiceFilterAttribute  and  TypeFilterAttribute  . Be an example to see how to use.

Copy the code
public class HomeController: Controller  
{
    [TypeFilter(typeof(FilterClass))]
    [ServiceFilter(typeof(FilterClass))]
    public IActionResult Index()
    {
        return View();
    }
}
Copy the code

  2.2 ServiceFilterAttribute 

   Actually see the name, some friends will be able to think, and it is based on dependency injection of a IFilterFactory , Service reinforces this word it is a dependency injection to achieve by getting services, we think of what? Is not GetService ()? Yes, in fact, it is this mechanism.

     To ServiceFilter registered on the type of container to be injected corresponding to rely, as in the following example, we must first register to the IOC FilterClass type container.

public void ConfigureServices(IServiceCollection services)
{
      services.AddSingleton<FilterClass>();
 
      services.AddMvc()
}

  Of course, if the type of construction requires FilterClass injection type, but also need to register IOC container can be used.

  ServiceFilterAttribute we look at the source code:

Copy the code
public class ServiceFilterAttribute : Attribute, IFilterFactory, IOrderedFilter
{
    public ServiceFilterAttribute([NotNull] Type type)
    {
        ServiceType = type;
    }

    public Type ServiceType { get; private set; }

    public int Order { get; set; }

    public IFilter CreateInstance([NotNull] IServiceProvider serviceProvider)
    {
        var service = serviceProvider.GetRequiredService(ServiceType);

        var filter = service as IFilter;
        if (filter == null)
        {
            throw new InvalidOperationException(Resources.FormatFilterFactoryAttribute_TypeMustImplementIFilter(
                typeof(ServiceFilterAttribute).Name,
                typeof(IFilter).Name));
        }

        return filter;
    }
}
Copy the code

  2.3  Type Filtering guest tribute

   Of course you can also choose to use this filter similar ServiceFilter TypeFilter filter, it also implements IFilterFactory interfaces, and can be used to create the dependency injection to filter through it. TypeFilter was called because it does not need to register the type of container can create a filter in dependency injection, we look at its code:

Copy the code
public class TypeFilterAttribute : Attribute, IFilterFactory, IOrderedFilter
{
    private ObjectFactory factory;

    public TypeFilterAttribute([NotNull] Type type)
    {
        ImplementationType = type;
    }

    public object[] Arguments { get; set; }

    public Type ImplementationType { get; private set; }

    public int Order { get; set; }

    public IFilter CreateInstance([NotNull] IServiceProvider serviceProvider)
    {
        if (this.factory == null)
        {
            var argumentTypes = Arguments?.Select(a => a.GetType())?.ToArray();

            this.factory = ActivatorUtilities.CreateFactory(ImplementationType, argumentTypes ?? Type.EmptyTypes);
        }

        return (IFilter)this.factory(serviceProvider, Arguments);
    }
}
Copy the code

Third, the conclusion

  Who saw an article on the friends I have noticed ServiceProvider and ActivatorUtilities  different on this article ServiceFilterAttribute and TypeFilterAttribute principle is to create a Filter by them, so the use of scenarios to see how everyone to use. In fact, I recently .NET Core source code, you can see everywhere interfaces, factory use dependency injection example of forming the extension point, in fact, Microsoft's previous extension points also with a lot of code, but not so open API, ASP.NET Core we see an "open" framework.

 

  GitHub: https://github.com/maxzhang1985/YOYOFx   if sleep also can ask Star , the welcome exchange.

 

  .NET Core open source learning group:  214 741 894  

 

Guess you like

Origin www.cnblogs.com/webenh/p/11605632.html