[英]Wrapping methods with different signatures, pre-and-post-invocation
How to avoid a pair of repetitive lines before and after invocations in sample below ? 在下面的示例中,如何避免在调用前后有一对重复的行? Details: This is compileable mock of what is real larger code.
详细信息:这是真正的较大代码的可编译模拟。 Generally it is a layer of proxy classes containing service clients with variety of APIs.
通常,它是代理类的一层,其中包含具有各种API的服务客户端。 The repetitive part is pre- and post- invocation for every method of every client.
重复部分是每个客户端的每种方法的调用前和调用后。 Unfortunately there is no single signature for all possible methods, the pre- and post- parts need a pointer to client's channel and context.
不幸的是,所有可能的方法都没有单一的签名,前置和后部都需要一个指向客户通道和上下文的指针。 Is it possible to apply something advanced like AOP, Generics, Delegates, Attributes etc. ?
是否可以应用高级功能,例如AOP,泛型,委托,属性等? Thank you
谢谢
using System;
namespace ConsoleApplication
{
class ClassServiceClient: IDisposable
{
public Object channel()
{
return "something";
}
public Object context()
{
return "something other";
}
}
class ClassA : ClassServiceClient
{
public Object methodA()
{
return "something other";
}
}
class ClassB : ClassServiceClient
{
public void methodB(string param)
{
return;
}
}
class ClassAProxy
{
public Object methodA()
{
using (ClassA client = new ClassA())
{
Program.preparation(client.channel()); //<---- repetitive part
Object result = client.methodA();
Program.postinvocation(client.context());//<---- repetitive part
return result;
}
}
}
class ClassBProxy
{
public void methodB(string param)
{
using (ClassB client = new ClassB())
{
Program.preparation(client.channel()); //<---- repetitive part
client.methodB(param);
Program.postinvocation(client.context());//<---- repetitive part
return;
}
}
}
class Program
{
public static void preparation(Object channel)
{
// Do something with channel
}
public static void postinvocation(Object context)
{
// Do something with context
}
static void Main(string[] args)
{
}
}
}
If you can use a common base class, you can easily use a public sealed method that does the invocation and a protected abstract method that does the logic, eg 如果可以使用公共基类,则可以轻松使用执行调用的公共密封方法和执行逻辑的受保护抽象方法,例如
class ProxyBase{
public void Method(params object[] args){
PreConditions();
Invoke(args);
PostConditions();
}
protected abstract void Invoke(object[] args);
}
class ClassAProxy{
protected override void Invoke(object[] args){
client.Method(args[0]);
}
}
You can achieve similar results functionally by declaring a InvocationHandler in your Program class that takes an action: 在程序类中声明一个采取措施的InvocationHandler,可以在功能上实现相似的结果:
class Program{
public static void Invoke(object[] args, Action action){
PreConditions();
action();
PostConditions();
}
}
class ClassAProxy{
public void MethodA(int i){
Program.Invoke(() => client.Something(i));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.