views:

280

answers:

4

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

A: 

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
As Ayende pointed out http://groups.google.com/group/castle-project-users/browse_thread/thread/d1c3b4464aad6043Location throwing an exception is a side effect. the same would happen if you useAssembly.Load(File.ReadAllBytes("Nhibernate.dll"));
Simon
A: 

This seems to be working for Castle:

private static bool IsDynamic(Type type)
{
    return type.Namespace == null;
}
But that is specific to the castle implementation. Might not be true for other proxy generators :(
Simon
This won't work with the trunk and the upcoming v2.2 because proxies now Do have a namespace
Krzysztof Koźmic
+5  A: 

type.Assembly.FullName.StartsWith("DynamicProxyGenAssembly2")

Ayende Rahien
need something not specific to castle
Simon
You want to detect if type is a DynamicProxy proxy. How is that NOT specific to Castle?
Krzysztof Koźmic
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
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 Koźmic
A: 

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);
SelflessCoder