Thomas Darimont
Erfahrenes Mitglied
Hallo!
Hier mal ein kleines Beispiel wie man unter .Net Dynamic Proxies in C# erzeugen kann:
Ausgabe:
Gruß Tom
Hier mal ein kleines Beispiel wie man unter .Net Dynamic Proxies in C# erzeugen kann:
C#:
using System;
using System.Collections.Generic;
using System.Text;
using RealProxy = System.Runtime.Remoting.Proxies.RealProxy;
using IMessage = System.Runtime.Remoting.Messaging.IMessage;
using ReturnMessage = System.Runtime.Remoting.Messaging.ReturnMessage;
using IMethodCallMessage = System.Runtime.Remoting.Messaging.IMethodCallMessage;
using TargetInvocationException = System.Reflection.TargetInvocationException;
namespace De.Tutorials.Training
{
class DynamicProxyExample
{
public static void Main(string[] args)
{
IBusinessService businessService = new SimpleProxy(typeof(IBusinessService), new BusinessServiceImpl()).GetTransparentProxy() as IBusinessService;
Console.WriteLine(businessService.BusinessOperation("Proxy"));
}
}
class SimpleProxy : RealProxy
{
object target;
public SimpleProxy(Type type, object target)
: base(type)
{
this.target = target;
}
public override IMessage Invoke(IMessage message)
{
IMethodCallMessage methodCallMessage = (IMethodCallMessage)message;
try
{
Console.WriteLine("Before: " + methodCallMessage.MethodName);
object result = target.GetType().GetMethod(methodCallMessage.MethodName, (Type[])methodCallMessage.MethodSignature).Invoke(target, methodCallMessage.InArgs);
Console.WriteLine("After: " + methodCallMessage.MethodName);
return new ReturnMessage(result, null, 0, methodCallMessage.LogicalCallContext, methodCallMessage);
}
catch (TargetInvocationException targetInvocationException)
{
return new ReturnMessage(targetInvocationException, methodCallMessage);
}
}
}
interface IBusinessService
{
string BusinessOperation(string args);
}
class BusinessServiceImpl
: IBusinessService
{
public string BusinessOperation(string args)
{
Console.WriteLine("Hallo " + args);
return args;
}
}
}
Ausgabe:
Code:
Before: BusinessOperation
Hallo Proxy
After: BusinessOperation
Proxy
Gruß Tom