Get the interface type of an interface proxy created without target

60 Views Asked by At

Considering model below:

public interface IFooBase
{
    void DoSomething();
}

public interface IFoo : IFooBase
{
}

A Castle.DynamicProxy interceptor:

public class Proxy : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        // Here need to know from which interface the proxy 
        // is generate (IFooBase or IFoo).
    }
}

And the proxies of IFooBase and IFoo generated using CreateInterfaceProxyWithoutTarget in the program.cs:

var generator = new ProxyGenerator();
var proxy = new Proxy();
var fooBase = generator.CreateInterfaceProxyWithoutTarget<IFooBase>(proxy);
var foo = generator.CreateInterfaceProxyWithoutTarget<IFoo>(proxy);
fooBase.DoSomething();
foo.DoSomething();

Inside the Intercept method, I need know from which interface type (IFooBase or IFoo) the proxy is generated. The only option I know is invocation.Method.DeclaringType which of course always returns FooBase type.

2

There are 2 best solutions below

3
Hossein Babamoradi On

you can use this code i use name of interface , you can compare type of them

public void Intercept(IInvocation invocation)
{

    var types = invocation.GetType().GetInterfaces();
    bool hasIFoo = false;
    bool hasIFooBase = false;
    foreach (var type in types)
    {
        if (type.Name == "IFoo")
        {
            hasIFoo = true;
        }
        if (type.Name == "IFooBase")
        {
            hasIFooBase = true;
        }
    }
    if (hasIFoo && hasIFooBase)
        Console.WriteLine("Implement IFooBase");
    else if (hasIFoo)
        Console.WriteLine("Implement IFoo");
    else
        Console.WriteLine("Implement Nothing");

}
0
Mahdi On

I found the answer by myself and share it here.

The code below for the interception of fooBase.DoSomething() returns IFooBase and for the foo.DoSomething() returns IFoo and IFooBase.

invocation.Proxy.GetType().GetInterfaces()