1

I'm experimenting with interceptors and dynamic proxies in Ninject and I've come across a situation where I really need to 'unwrap' a proxied instance of a class to the base instance. Is this possible? It seems like it should be pretty simple but I can't find a way to do it.

This successfully calls the interceptor:

[MyInterceptorAttribute()]
public virtual int MethodCall(int input)

But then I want to find and instantiate the non-proxied versions of each class where the attribute occurs:

var methods = assembly.GetTypes()
            .SelectMany(t => t.GetMethods())
            .Where(m => Attribute.IsDefined(m, typeof(MyInterceptorAttribute)))
            .ToList();

foreach(var method in methods) {
    // The proxied instance
    instance = kernel.Get(method.DeclaringType);
}

How can I get the non-proxied instance?

Hubris
  • 1,842
  • 2
  • 18
  • 26

2 Answers2

2

To my knowledge Ninject itself does not offer any specific interface for accessing the proxy target. With some kinds of proxies (class proxy) this is not even possible, because the proxy actually inherits from the proxied type and thus there is no sensible distinction when accessing the proxy.

If you're using Ninject with castle dynamic proxy, this SO Q/A show methods on how to access the proxied type for the other kinds of proxies.

BatteryBackupUnit
  • 12,934
  • 1
  • 42
  • 68
0

If you have access to the activation context, you can do the following:

var reference= new InstanceReference()
        {
            Instance = yourWrappedObject
        };
new DynamicProxyProxyFactory(context.Kernel).Unwrap(context,reference);

return reference.Instance;
Daniel B
  • 4,145
  • 1
  • 21
  • 21