7

I am using castle DynamicProxy and was wondering if there is a way of detecting if a Type is a proxy without referencing Castle DynamicProxy?

So while I am using Castle DynamicProxy as an example I would like code that would work for any in memory generated type.

var generator = new ProxyGenerator();

var classProxy = generator.CreateClassProxy<Hashtable>();
Debug.WriteLine(classProxy.GetType().Is....);

var interfaceProxy = generator.CreateInterfaceProxyWithoutTarget<ICollection>();
Debug.WriteLine(interfaceProxy.GetType().Is....);

Thanks

Simon
  • 33,714
  • 21
  • 133
  • 202

4 Answers4

10
type.Assembly.FullName.StartsWith("DynamicProxyGenAssembly2")
Farhad Jabiyev
  • 26,014
  • 8
  • 72
  • 98
Ayende Rahien
  • 22,925
  • 1
  • 36
  • 41
  • need something not specific to castle – Simon Jul 29 '09 at 00:51
  • 2
    You want to detect if type is a DynamicProxy proxy. How is that NOT specific to Castle? – Krzysztof Kozmic Jul 29 '09 at 05:58
  • I am using DynamicProxy as an example so people can easily know what i am talking about. But i am looking for code that will tell me if it is a runtime generated type. – Simon Jul 29 '09 at 12:07
  • there is no single solution for that. I'm afraid. You can generate type, save the assembly you generated it to to file. How would you know if it was generated, or was there from the beginning? Why do you need that at all? – Krzysztof Kozmic Aug 02 '09 at 17:29
  • @JeffN825: that's what I used... :) – TDaver Oct 05 '12 at 12:27
3

You could make your dynamic type implements a specific interface:

public interface IDynamicProxy { }

...

ProxyGenerator generator = new ProxyGenerator();

var classProxy = generator.CreateClassProxy(typeof(Hashtable), new[] {typeof(IDynamicProxy)});
Debug.WriteLine(classProxy is IDynamicProxy);


var interfaceProxy = generator.CreateInterfaceProxyWithoutTarget(typeof(ICollection), new[] { typeof(IDynamicProxy) });
Debug.WriteLine(interfaceProxy is IDynamicProxy);
Jeff Cyr
  • 4,774
  • 1
  • 28
  • 42
0

so far i have this fugly code

    private static bool IsDynamic(Type type)
    {
        try
        {
            var location = type.Assembly.Location;
            return false;
        }
        catch (NotSupportedException)
        {
            return true;
        }
    }
Simon
  • 33,714
  • 21
  • 133
  • 202
  • As Ayende pointed out http://groups.google.com/group/castle-project-users/browse_thread/thread/d1c3b4464aad6043 Location throwing an exception is a side effect. the same would happen if you use Assembly.Load(File.ReadAllBytes("Nhibernate.dll")); – Simon Jul 29 '09 at 00:54
0

This seems to be working for Castle:

private static bool IsDynamic(Type type)
{
    return type.Namespace == null;
}