Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

[Solution] Analysis of the principle of AOP and use of Castle, Autofac and Unity frameworks

2025-02-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >

Share

Shulou(Shulou.com)06/01 Report--

AOP introduction

Aspect-oriented programming (Aspect Oriented Programming, abbreviated as AOP) is a technology that realizes the unified maintenance of program functions through pre-compilation and runtime dynamic agents.

AOP is the continuation of OOP and is a hot spot in software development.

Commonly used for:

Authentication

Caching

Lazy loading

Transactions

Basic principles of AOP

Ordinary class

one

two

three

four

five

six

seven

eight

nine

Class Person: MarshalByRefObject

{

Public string Say ()

{

Const string str = "Person's say is called"

Console.WriteLine (str)

Return str

}

}

Proxy class

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

fourteen

fifteen

sixteen

Public class Proxy: RealProxy where T: new ()

{

Private object _ obj

Public Proxy (object obj)

Base (typeof (T))

{

_ obj = obj

}

Public override IMessage Invoke (IMessage msg)

{

Console.WriteLine ("{0}: before Invoke", DateTime.Now)

Var ret = ((IMethodCallMessage) msg) .MethodBase.Invoke (_ obj, null)

Console.WriteLine ("{0}: after Invoke", DateTime.Now)

Return new ReturnMessage (ret, null, 0, null, null)

}

}

Execution

one

two

three

four

five

six

seven

eight

nine

ten

Static void Main (string [] args)

{

Var per = new Proxy (new Person ()) .GetTransparentProxy () as Person

If (per! = null)

{

Var str = per.Say ()

Console.WriteLine ("return value:" + str)

}

Console.ReadKey ()

}

AOP framework

AOP has dynamic proxies and static IL weaving.

This section mainly introduces the dynamic proxy mode, static can refer to PostSharp.

Castle Core

Principle: the essence is to create a proxy class that inherits the original class. Override virtual method to realize AOP function.

Just quote:

Install-Package Castle.Core

(over version 2.5 of Castle, content in Castle.DynamicProxy2.dll has been integrated into Castle.Core.dll.)

Simple Class

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

fourteen

fifteen

sixteen

seventeen

eighteen

nineteen

Public abstract class Person

{

Public virtual void SayHello ()

{

Console.WriteLine ("I am the {0} method", "SayHello")

}

Public virtual void SayName (string name)

{

Console.WriteLine ("I am the {0} method, parameter values: {1}", "SayName", name)

}

Public abstract void AbstactSayOther ()

Public void SayOther ()

{

Console.WriteLine ("I am the {0} method", "SayOther")

}

}

Interceptor

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

fourteen

fifteen

sixteen

seventeen

eighteen

nineteen

twenty

twenty-one

twenty-two

Public class SimpleInterceptor: StandardInterceptor

{

Protected override void PreProceed (IInvocation invocation)

{

Console.WriteLine ("before the interceptor calls the method, the method name is: {0}." , invocation.Method.Name)

}

Protected override void PerformProceed (IInvocation invocation)

{

Console.WriteLine ("the interceptor starts calling the method with the name: {0}." , invocation.Method.Name)

Var attrs = invocation.MethodInvocationTarget.Attributes.HasFlag (MethodAttributes.Abstract); / / filter abstract method

If (! attrs)

{

Base.PerformProceed (invocation); / / the real method invocation.Proceed () will be called here

}

}

Protected override void PostProceed (IInvocation invocation)

{

Console.WriteLine ("after the interceptor calls the method, the method name is: {0}." , invocation.Method.Name)

}

}

Main

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

fourteen

fifteen

sixteen

seventeen

eighteen

nineteen

twenty

twenty-one

twenty-two

twenty-three

Static void Main (string [] args)

{

Var generator = new ProxyGenerator (); / / instantiate [proxy class generator]

Var interceptor = new SimpleInterceptor (); / / instantiate [interceptor]

/ / use [proxy Class Builder] to create a Person object instead of using the new keyword to instantiate

Var person = generator.CreateClassProxy (interceptor)

Console.WriteLine ("current type: {0}, parent type: {1}", person.GetType (), person.GetType () .BaseType)

Console.WriteLine ()

Person.SayHello () / / intercept

Console.WriteLine ()

Person.SayName ("Never, C"); / / interception

Console.WriteLine ()

Person.SayOther (); / / normal method, cannot be intercepted

Person.AbstactSayOther (); / / Abstract methods that can intercept

Console.ReadLine ()

}

Castle Windsor

Characteristic AOP

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

Public interface IPerson

{

Void Say ()

}

[Interceptor (typeof (LogInterceptor))]

Public class Person: IPerson

{

Public void Say ()

{

Console.WriteLine ("Person's Say Method is called!")

}

}

one

two

three

four

five

six

seven

eight

nine

Public class LogInterceptor: IInterceptor

{

Public void Intercept (IInvocation invocation)

{

Console.WriteLine ("{0}: before intercepting {1} method {2},", DateTime.Now.ToString ("O"), invocation.InvocationTarget.GetType () .BaseType, invocation.Method.Name)

Invocation.Proceed ()

Console.WriteLine ("{0}: after intercepting {1} method {2},", DateTime.Now.ToString ("O"), invocation.InvocationTarget.GetType () .BaseType, invocation.Method.Name)

}

}

one

two

three

four

five

six

seven

eight

nine

ten

eleven

Static void Main (string [] args)

{

Using (var container = new WindsorContainer ())

{

Container.Register (Component.For ())

Container.Register (Component.For ())

Var person = container.Resolve ()

Person.Say ()

}

Console.ReadKey ()

}

Non-invasive AOP

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

Public interface IPerson

{

Void Say ()

}

Public class Person: IPerson

{

Public void Say ()

{

Console.WriteLine ("Person's Say Method is called!")

}

}

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

fourteen

fifteen

sixteen

seventeen

eighteen

nineteen

twenty

twenty-one

Internal static class LogInterceptorRegistrar

{

Public static void Initialize (WindsorContainer container)

{

Container.Kernel.ComponentRegistered + = Kernel_ComponentRegistered

}

Private static void Kernel_ComponentRegistered (string key, IHandler handler)

{

Handler.ComponentModel.Interceptors.Add (new InterceptorReference (typeof (LogInterceptor)

}

}

Public class LogInterceptor: IInterceptor

{

Public void Intercept (IInvocation invocation)

{

Console.WriteLine ("{0}: before intercepting {1} method {2},", DateTime.Now.ToString ("O"), invocation.InvocationTarget.GetType () .BaseType, invocation.Method.Name)

Invocation.Proceed ()

Console.WriteLine ("{0}: after intercepting {1} method {2},", DateTime.Now.ToString ("O"), invocation.InvocationTarget.GetType () .BaseType, invocation.Method.Name)

}

}

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

Static void Main (string [] args)

{

Using (var container = new WindsorContainer ())

{

Container.Register (Component.For ()); / / inject the interceptor first

LogInterceptorRegistrar.Initialize (container)

Container.Register (Component.For ())

Var person = container.Resolve ()

Person.Say ()

}

Console.ReadKey ()

}

Autofac

Install-Package Autofac.Aop

Bind through property label

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

fourteen

fifteen

sixteen

seventeen

eighteen

nineteen

twenty

twenty-one

twenty-two

twenty-three

Class LogInterceptor: IInterceptor

{

Public void Intercept (IInvocation invocation)

{

Console.WriteLine ("{0}: before intercepting {1} method {2},", DateTime.Now.ToString ("O"), invocation.InvocationTarget.GetType () .BaseType, invocation.Method.Name)

Invocation.Proceed ()

Console.WriteLine ("{0}: after intercepting {1} method {2},", DateTime.Now.ToString ("O"), invocation.InvocationTarget.GetType () .BaseType, invocation.Method.Name)

}

}

Public interface IPerson

{

Void Say ()

}

[Intercept (typeof (LogInterceptor))]

Public class Person: IPerson

{

Public void Say ()

{

Console.WriteLine ("Person's Say Method is called!")

}

}

Enable interceptor execution

one

two

three

four

five

6

7

8

nine

ten

11

Static void Main (string [] args)

{

Var builder = new ContainerBuilder ()

Builder.RegisterType (). As (). EnableInterfaceInterceptors ()

Builder.RegisterType ()

Using (var container = builder.Build ())

{

Container.Resolve () .Say ()

}

Console.ReadLine ()

}

Or adopt a non-invasive approach (it is still possible to remove the features on class)

one

two

three

four

five

six

seven

eight

nine

ten

eleven

Static void Main (string [] args)

{

Var builder = new ContainerBuilder ()

Builder.RegisterType (). As (). EnableInterfaceInterceptors (). InterceptedBy (typeof (LogInterceptor))

Builder.RegisterType ()

Using (var container = builder.Build ())

{

Container.Resolve () .Say ()

}

Console.ReadLine ()

}

Unity

Unity provides three interceptors by default: TransparentProxyInterceptor, InterfaceInterceptor, and VirtualMethodInterceptor.

TransparentProxyInterceptor: the proxy implementation is based on .NET Remoting technology, which intercepts all functions of the object. The disadvantage is that the intercepted type must be derived from MarshalByRefObject.

InterfaceInterceptor: only one interface can be intercepted. The advantage is that it can be intercepted as long as the target type implements the specified interface.

VirtualMethodInterceptor: intercept the virtual function. The disadvantage is that if the intercepted type does not have a virtual function, it cannot be intercepted. At this time, if the type implements a specific interface, it can be used instead.

Install-Package Unity.Interception

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

Public class MyHandler: ICallHandler

{

Public int Order {get; set;} / / this is a member of ICallHandler, indicating the order of execution

Public IMethodReturn Invoke (IMethodInvocation input, GetNextHandlerDelegate getNext)

{

Console.WriteLine ("before method execution")

/ / pre-execution processing of the insert method before this

Var retvalue = getNext () (input, getNext); / / execute the method here

/ / after that, the processing after the execution of the insert method

Console.WriteLine ("after method execution")

Return retvalue

}

}

one

two

three

four

five

six

seven

Public class MyHandlerAttribute: HandlerAttribute

{

Public override ICallHandler CreateHandler (IUnityContainer container)

{

Return new MyHandler (); / / returns MyHandler

}

}

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

Public interface IPerson

{

Void Say ()

}

[MyHandler]

Public class Person: IPerson

{

Public virtual void Say ()

{

Console.WriteLine ("Person's Say Method is called!")

}

}

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

fourteen

fifteen

sixteen

seventeen

eighteen

Static void Main (string [] args)

{

Using (var container = new UnityContainer ())

{

Container.AddNewExtension ()

/ / 1.TransparentProxyInterceptor

/ container.Configure () .SetInterceptorFor (new TransparentProxyInterceptor ())

/ / 2.InterfaceInterceptor (use 1, 2, 3, this is the least intrusive)

Container.Configure () .SetInterceptorFor (new InterfaceInterceptor ()

/ / 3.VirtualMethodInterceptor

/ container.Configure () .SetInterceptorFor (new VirtualMethodInterceptor ())

Container.RegisterType ()

Container.Resolve () .Say ()

}

Console.ReadKey ()

}

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Network Security

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report