Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting underlying type of a proxy object

I'm using Castle DynamicProxy and my ViewModels are a proxy, something like this:

namespace MyApplication.ViewModels
{
   public class MyViewModel : BaseViewModel, IMyViewModel
   {
   }
}

a proxy of my viewmodel looks like this though:

{Name = "IRootViewModelProxyffecb133f590422098ca7c0ac13b8f98" FullName = "IRootViewModelProxyffecb133f590422098ca7c0ac13b8f98"}

I want to get the actual type or namespace of the actual type that is being proxied. Is there any way to do this? I want something that returns MyApplication.ViewModels.MyViewModel type. If I'm using concreate class as proxies, BaseType returns the actual class that is being proxied, but when using the interface, BaseType would return System.Object.

like image 270
Hadi Eskandari Avatar asked Sep 12 '09 17:09

Hadi Eskandari


People also ask

What is a proxy object?

A proxy object acts as an intermediary between the client and an accessible object. The purpose of the proxy object is to monitor the life span of the accessible object and to forward calls to the accessible object only if it is not destroyed.

What is proxy in console log?

In JavaScript, proxies (proxy object) are used to wrap an object and redefine various operations into the object such as reading, insertion, validation, etc. Proxy allows you to add custom behavior to an object or a function.

What is proxy MDN?

Description. The Proxy object allows you to create an object that can be used in place of the original object, but which may redefine fundamental Object operations like getting, setting, and defining properties. Proxy objects are commonly used to log property accesses, validate, format, or sanitize inputs, and so on.

What is ES6 proxy?

ES6 proxies sit between your code and an object. A proxy allows you to perform meta-programming operations such as intercepting a call to inspect or change an object's property. The following terminology is used in relation to ES6 proxies: target. The original object the proxy will virtualize.


2 Answers

It seems you can do the following to get the actual type:

(proxy As IProxyTargetAccessor).DynProxyGetTarget().GetType()
like image 122
Hadi Eskandari Avatar answered Oct 22 '22 03:10

Hadi Eskandari


If you are proxying a class and not an interface, you can get the underlying type like this:

var unproxiedType = ProxyUtil.GetUnproxiedType(proxy);

If you don't have access to ProxyUtil this will also work:

private static Type GetUnproxiedType(object source)
{
   var proxy = (source as IProxyTargetAccessor);

   if (proxy == null)
     return source.GetType();

   return proxy.GetType().BaseType;            
}
like image 28
Gregor Slavec Avatar answered Oct 22 '22 03:10

Gregor Slavec