. Net dynamic Agents, AOP
directly on the code.
/***************************************** * Author:jinshuai * * E-mail:[email protected] * * date:2016-04-28 * * * **************************************/usingSystem;usingSystem.Collections.Generic;usingSystem.Runtime.Remoting;usingSystem.Runtime.Remoting.Messaging;usingSystem.Runtime.Remoting.Proxies;namespacedynamicproxy.core{/// <summary> ///Agent Factory/// </summary> /// <typeparam name= "T" ></typeparam> Public classProxyfactory<t> { Public StaticT Create (t obj, dictionary<string, dynamicaction> proxymethods =NULL) { varProxy =NewDynamicproxy<t> (obj) {proxymethods =Proxymethods}; return(T) proxy. Gettransparentproxy (); } } /// <summary> ///Dynamic Proxy Classes/// </summary> /// <typeparam name= "T" ></typeparam> Public classDynamicproxy<t>: RealProxy {Private ReadOnlyT _targetinstance =default(T); Publicdictionary<string, dynamicaction> proxymethods {Get;Set; } Publicdynamicproxy (T targetinstance):Base(typeof(T)) {_targetinstance=TargetInstance; } Public OverrideIMessage Invoke (IMessage msg) {varreqmsg = Msg asIMethodCallMessage; if(Reqmsg = =NULL) { return NewReturnMessage (NewException ("The call failed! "),NULL); } vartarget = _targetinstance asMarshalByRefObject; if(target = =NULL) { return NewReturnMessage (NewException ("The call failed! Please inherit the target object from System.MarshalByRefObject"), reqmsg); } varMethodName =Reqmsg.methodname; Dynamicaction Actions=NULL; if(Proxymethods! =NULL&&Proxymethods.containskey (MethodName)) {Actions=Proxymethods[methodname]; } if(Actions! =NULL&& actions. Beforeaction! =NULL) {actions. Beforeaction (); } varresult =remotingservices.executemessage (target, reqmsg); if(Actions! =NULL&& actions. Afteraction! =NULL) {actions. Afteraction (); } returnresult; } } /// <summary> ///methods to be executed by the dynamic agent/// </summary> Public classdynamicaction {/// <summary> ///Execute before the target method is executed/// </summary> PublicAction Beforeaction {Get;Set; } /// <summary> ///Executes after the target method is executed/// </summary> PublicAction Afteraction {Get;Set; } }}
DEMO:
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingDynamicproxy.core;namespacedynamicproxy.demo{classProgram {Static voidMain (string[] args) { varProxymotheds =Newdictionary<string, dynamicaction>(); //key is proxies ' s methodName, value is ActionsProxymotheds.add ("ADD",Newdynamicaction () {beforeaction=NewAction (() = Console.WriteLine ("before Doing ....")), Afteraction=NewAction (() = Console.WriteLine ("After Doing ....")) }); varuser =NewUser (); //Proxy for User vart = proxyfactory<user>. Create (user, proxymotheds); intCount =0; T.add ("Tom", -, outcount); T.sayname (); Console.WriteLine (count); Console.read (); } }}
You can also go to my github and get the full project directly Https://github.com/jinshuai/DynamicProxy.NET
. Net dynamic Agents, AOP