c# - 包装 WCF 调用 - 发出捕获 lambda 或更好的方法?

标签 c# wcf lambda reflection.emit

为了不陷入 X-Y 问题,我想做的是包装 WCF 调用,以便自动实现重试(和其他规则),但我不知道前面的所有接口(interface)时间(这是一个中间件)。所以我基本上采用通用 DuplexChannelFactory<TChannel>.CreateChannel() 的输出,然后再次将其设为代理。在 SO 上有几个关于包装调用和重试等的不同问题,但它们都没有处理未知数量的接口(interface),您需要一个完全通用的解决方案。

所以我想在每次客户端调用时注入(inject)代码,但我希望我的对象实现 TChannel界面直接。所以我想到了使用 Reflection.Emit对将保存 DuplexChannelFactory<> 结果的“基础”对象进行子类化调用,然后连接它自己的方法,包括重试功能。这是我在工厂方法中最初的“对象创建”:

    static TInterface generateImplementor<TInterface, Tcallback>(params object[] parameters) where TInterface : class
    {
        // Get the information about the interface.  This is necessary because this
        // is a generic method, where literally anything could be passed in
        Type interfaceType = typeof(TInterface);

        // Create the assembly and module to hold the object created
        // <snip>

        // Define a public class based on the passed-in interface name.
        TypeBuilder generatedType = myModule.DefineType(interfaceType.Name + "Implementor",
            TypeAttributes.Public, typeof(ForwarderBase<TInterface, Tcallback>),
            new Type[] { interfaceType });

        // Implement 'TInterface' interface.
        generatedType.AddInterfaceImplementation(interfaceType);

好的,但是从那里去哪里呢?这类似于我想出的静态编码,但我需要用 Reflection.Emit 在那里进行最后两次调用。 .

class ForwarderBase<T, Tcallback>
{
    protected T proxyObj;
    public ForwarderBase(Tcallback callbackObj)
    {
        proxyObj = DuplexChannelFactory<T>.CreateChannel(callbackObj, "Endpoint");
    }

    private void noRetWrapper(Action call)
    {
        // Inject extra code here possibly
        try
        {
            call();
        }
        catch (Exception ex)
        {
            // all of this in a retry loop possibly, or whatever
            Console.WriteLine("Exception is: " + ex.ToString());
        }
    }

    private TRet retWrapper<TRet>(Func<TRet> call)
    {
        // Inject extra code here possibly
        try
        {
            return call();
        }
        catch (Exception ex)
        {
            // all of this in a retry loop possibly, or whatever
            Console.WriteLine("Exception is: " + ex.ToString());
        }
        return default(TRet);
    }

    // Dynamically emit these two, as depending on T, there will be an arbitrary number, with arbitrary arguments

    void firstMethod(int x)
    {
        // Lambda captures the arguments
        noRetWrapper(() => proxyObj.noReturnMethodCall(x));
    }

    int secondMethod(int firstParam, double secondParam, string thirdParam)
    {
        // Lambda captures the arguments
        return retWrapper(() => return proxyObj.returningMethodCall(firstParam, secondParam, thirdParam));
    }

}

所以我没问题Emit除了捕获 lambda 之外,最后两个方法(以及任何数量的方法,实际上应该没问题)。这是必要的,否则上面的两个“包装器”会爆炸成任何可能数量的类型和返回值组合。

那么我该如何Emit我需要的捕获 lambda?作为this question说,没有 Func<...>等等,因此我的Func , 和一个 Action方法在这里。

最佳答案

这就是Castle DynamicProxy (和类似的图书馆)是为了。使用它,您可以编写一个拦截器类,每次调用代理上的方法时都会调用该拦截器类。该代理是通过调用方法自动创建的。

拦截器可能如下所示:

class IgnoreExceptionsInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        try
        {
            invocation.Proceed();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
            invocation.ReturnValue = GetDefault(invocation.Method.ReturnType);
        }
    }

    private static object GetDefault(Type type)
    {
        if (type.IsValueType && type != typeof(void))
        {
            return Activator.CreateInstance(type);
        }
        return null;
    }
}

( GetDefault() has to be used, because there is no direct equivalent of default(T) that would take a Type. )

有了接口(interface) IFoo 及其实现 Foo,您可以像这样使用它:

var generator = new ProxyGenerator();
IFoo fooProxy = generator.CreateInterfaceProxyWithTargetInterface<IFoo>(
    new Foo(), new IgnoreExceptionsInterceptor());
fooProxy.Whatever();

关于c# - 包装 WCF 调用 - 发出捕获 lambda 或更好的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15866591/

相关文章:

c# - 串口通讯显示

c# - 并非所有属性都在 WCF 调用中发送或接收

java8 对函数结果的使用改变了进一步的处理

java - AWS Lambda 获取空值作为查询字符串

c# - 编译 C# 不安全代码

javascript - 正则表达式 从 Js 转换为 C#

c# - 在 C# 中嵌入 boo,无法识别正在执行的程序集

c# - 从 C# Windows 窗体应用程序在 SQLite 数据库中记录错误

c# - 通过 WCF 桥接 NSB

c++ - 通过 clang-format 格式化 lambda 背后的逻辑是什么?