Three ways to implement "pluggable" AOP programming in. NET core (with source code)

Source: Internet
Author: User
Tags httpcontext

A look at the headline will certainly suggest that AOP programming is implemented using dynamic weaving, but this is not the focus of the author's discussion in this article.

This article discusses three other ways that can be implemented in Netcore, filter, which is technically AOP in the strict sense,dynamicproxy (dynamic proxy mode, which is not new in Java), Middleware (AOP approach implemented by Netcore middleware)

What is AOP programming

In the software industry, AOP is the abbreviation for Aspect oriented programming, which means: face-cutting programming, through the pre-compilation method and runtime dynamic agent to implement the unified maintenance of the program functions of a technology. AOP is a continuation of OOP, a hotspot in software development, an important content in the spring framework, and a derivative model of functional programming. AOP enables the isolation of parts of the business logic, which reduces the coupling between parts of the business logic, improves the reusability of the program, and improves the efficiency of development.

In the vernacular is: to ensure that the principle of open and closed, without modifying a module (or function) of any line of code, so as to achieve the horizontal expansion of the module.

Pluggable: Even if you discard AOP, the core content can still run, reducing coupling and improving reusability.

Create an ASP. NET CORE Webapi project that "can say hello, xxx,"

Create a project step here to skip, hehe.

We assume a simplest "Say hello" as a project requirement, passing a name through a URL and returning "Hello {name}". So create a simple model Peoplemodel, create an interface Isay, and implement the "Hello {name}" feature in Isay with say.

1      Public Interface Isay 2     {3        peoplemodel SayHello (Peoplemodel peoplemodel); 4     }
1      Public classSay:isay2     {3          PublicPeoplemodel SayHello (Peoplemodel peoplemodel)4         {5Peoplemodel.name = $"Hello {peoplemodel.name}";6             returnPeoplemodel;7         }8}
1      Public classPeoplemodel2     {3          Public stringName {Get;Set; } ="";4          Public intAge {Get;Set; }5          Public intSex {Get;Set; }6}

Create an MVC controller again

1[Route ("Api/[controller]")]2 [Apicontroller]3      Public classDemocontroller:controllerbase4     {5 [HttpGet]6          PublicPeoplemodel Get ([fromquery] Peoplemodel Peoplemodel)7         {8             returnSay.sayhello (Peoplemodel);9         }Ten}

Very simple, do not explain, so as not to waste space.

Dynamicproxy Way

The way of dynamic proxies has appeared early in Java, as in the spring framework. The two frameworks, which utilize AUTOFAC and castle in net, can also implement dynamic proxies.

The framework that needs to be used is as follows:

AUTOFAC: Provides container control
Autofac.Extensions.DependencyInjection: Extending the AUTOFAC Dependency Injection
Autofac.Extras.DynamicProxy: Extending the AUTOFAC dynamic agent
Castle.core: Using dynamic proxy implementations

Believe AUTOFAC many friends are not unfamiliar, and with the castle framework can implement dynamic proxy mode, we create a new interceptor class, called Injectinterceptor, and must be implemented Iinterceptor (The interface is in Castle.dynamicproxy), the complete code is as follows:

1 usingSystem;2 usingCastle.dynamicproxy;3 4 namespaceInterceptDemo.Intercepts.Inject5 {6      Public classInjectinterceptor:iinterceptor7     {8          Public Virtual voidIntercept (iinvocation invocation)9         {Ten preproceed (invocation); One invocation. Proceed (); A postproceed (invocation); -         } -  the         Private voidpreproceed (iinvocation invocation) -         { -Console.WriteLine ($"{DateTime.Now} inject interceptor invoke Preproceed");  -         } +  -         Private voidpostproceed (iinvocation invocation) +         { AConsole.WriteLine ($"{DateTime.Now} inject interceptor invoke Postproceed"); at         } -     } -}

When inheriting the Iinterceptor interface, it is necessary to implement the Intercept virtual method, which will pass the iinvocation interface parameters, and calling the proceed function will implement the function outside the method body, which is a function other than the tangent plane. Using only the feature to implement the AOP method, we slightly modified say this class, add a sentence:[Intercept (typeof (injectinterceptor))]

Of course, you also need to implement the registration in AUTOFAC, the code is as follows:

var New Containerbuilder (); builder. Populate (services); builder. Registertype<Say> (). As<isay>(). Enableinterfaceinterceptors (); builder. Registertype<InjectInterceptor> ();

Filter mode

The way of the filter is more simple, in the ASP. NET Framework, the use of filters is very much, the author does not introduce, directly paste code:

1      Public classActionfilter:actionfilterattribute2     {3          Public Override voidonactionexecuting (actionexecutingcontext context)4         {5Console.WriteLine ($"{DateTime.Now} on action exceuting");6         }7 8          Public Override voidonactionexecuted (actionexecutedcontext context)9         {TenConsole.WriteLine ($"{DateTime.Now} on action exceuted"); One         } A}

Middleware Way

Not only can the middleware implement custom pipelines, but it can also be programmed as AOP for Netcore invoke. Let's start by building an extension class for Applicationbuilder .

 1  public  static  class   Intercepthandler  Span style= "color: #008080;" >2   { 3  public  static  iapplicationbuilder useinterceptmiddleware (this   Iapplicationbuilder app)  4   return  app. Usemiddleware<interceptmiddlware> ();  6   7
      } 

Build a second middleware

1 usingSystem;2 usingSystem.Threading.Tasks;3 usingMicrosoft.AspNetCore.Http;4 5 namespaceInterceptDemo.Intercepts.Middleware6 {7      Public classInterceptmiddlware8     {9         Private ReadOnlyrequestdelegate _next;Ten          One          PublicInterceptmiddlware (requestdelegate next) A         { -_next =Next; -         } the  -          Public AsyncTask Invoke (HttpContext context) -         { - preproceed (context); +             await_next (context); - postproceed (context); +         } A  at         Private voidPreproceed (HttpContext context) -         { -Console.WriteLine ($"{DateTime.Now} middleware invoke Preproceed"); -         } -  -         Private voidPostproceed (HttpContext context) in         { -Console.WriteLine ($"{DateTime.Now} middleware invoke Postproceed"); to         } +     } -}

The operation results are as follows

Summarize

There are many ways in which AOP can be used in Netcore, including the excellent open source framework in the country Asp.netcore can also implement AOP programming patterns.

The three kinds of AOP methods provided by the author can be applied as follows

Filter: Web processing-level services such as authentication, parameter validation, processing time, and so on.

Dynamicproxy: Decoupling and reusing services between functional modules.

The underlying services, such as communication between middleware:request and response, can also be implemented with custom pipelines if necessary.

Thanks for reading!

Source Address: Https://github.com/steveleeCN87/C-.three.aop.programming

Three ways to implement "pluggable" AOP programming in. NET core (with source code)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.