Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top