How to detect if a Type is a generated DynamicProxy without referencing Castle DynamicProxy?
-
19-09-2019 - |
Question
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
Solution 3
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;
}
}
OTHER TIPS
type.Assembly.FullName.StartsWith("DynamicProxyGenAssembly2")
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);
This seems to be working for Castle:
private static bool IsDynamic(Type type)
{
return type.Namespace == null;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow