views:

82

answers:

3

Dear ladies and sirs.

The AppDomain.TypeResolve is mysterious in my eyes. Can someone provide a sample code that triggers this event?

Thanks.

A: 

Type t = Type.GetType("Class1"); will do it.

From MSDN: "The TypeResolve event occurs when the common language runtime is unable to determine the assembly that can create the requested type. This can occur if the type is defined in a dynamic assembly, or the type is not defined in a dynamic assembly but the runtime does not know which assembly the type is defined in. The latter situation can occur when Type..::.GetType is called with a type name that is not qualified with the assembly name."

dkackman
Stupid me, in my test I used the fully qualified type name. Really stupid.
mark
Hehe. I make those kind of mistakes all the time.
dkackman
A: 

MSDN is pretty clear on when this event is raised:

The TypeResolve event occurs when the common language runtime is unable to determine the assembly that can create the requested type. This can occur if the type is defined in a dynamic assembly, or the type is not defined in a dynamic assembly but the runtime does not know which assembly the type is defined in. The latter situation can occur when Type.GetType is called with a type name that is not qualified with the assembly name.

This code will trigger the event:

AppDomain.CurrentDomain.TypeResolve += delegate(object sender, ResolveEventArgs e)
{
    Console.WriteLine("Trying to resolve '{0}'", e.Name);
    return null;
};

Type type = Type.GetType("SomeNamespace.SomeTypeWithoutAssemblyQualifier");
bobbymcr
A: 

The AppDomain.TypeResolve event will fire any time you request a type that can't be resolved by default. Normally, this will not happen, since your depedencies will always be in the same location as your executable (by default) or in the GAC.

However, it's easy to force it to occur. Just do:

Type badType = Type.GetType("IDontExist");

Since the type doesn't exist, it'll call the event to try to "find" the type.

Reed Copsey