Search code examples
.netnew-operator

Can I alter how types are resolved and instantiated in .NET?


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.


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