tags:

views:

127

answers:

5

In some languages you can override the "new" keyword to control how types are instantiated. You can't do this directly in .NET. However, I was wondering if there is a way to, say, handle a "Type not found" exception and manually resolve a type before whoever "new"ed up that type blows up?

I'm using a serializer that reads in an xml-based file and instantiates types described within it. I don't have any control over the serializer, but I'd like to interact with the process, hopefully without writing my own appdomain host.

Please don't suggest alternative serialization methods.

A: 

You should check out Reflection and the Activator class. They will allow you to create objects from strings. Granted, the object has to be in one of the assemblies that you have access to.

MagicKat
+4  A: 

You can attach an event handler to AppDomain.CurrentDomain.AssemblyResolve to take part in the process.

Your EventHandler should return the assembly that is responsible for the type passed in the ResolveEventArgs.

You can read more about it at MSDN

Abe Heidebrecht
Note: This is problematic on Mono.
leppie
A: 

Will, can you give an example of what the XML is like, and how it got to XML? Is it simply an xml-serialized object that you want to deserialize (rehydrate)? Or is it a description of a Type that you want to create?

I just need a bit of context here to get my head around your dilemma.

cranley
+1  A: 

There's also the AppDomain.TypeResolve event that you can override.

Peter Ritchie
A: 

select isn't broken discusses how to look at it differently - the fault may be in your design not your tooling.

I think that trying to get "new" to do something else is going to be the wrong approach.

Think of why operator overloading has to be used with caution - it's counter-intuitive and hard to debug when there are hidden changes in the language semantics.

Step back and look at the design in a larger context, try to find a more sensible way to solve the problem.

Anthony
I think its more elegant to help the process than go and load every friggen assembly I find, blindly, in hopes I get the type I need before deserialization blows up.
Will
I'm not saying you should "load every assembly blindly". That's a symptom of the problem. Try do find a design that is not prone to that symptom at all.
Anthony