Throw an exception for unregistered types ?

Jul 25, 2008 at 7:39 AM
Edited Jul 25, 2008 at 1:09 PM
Hi,

Is there any way for a Unity container to throw an exception for unregistered types ?

I explain myself. Suppose we've got a type "Foo" that we forgot to register in a Unity container. The default behavior for the container when you call "container.Resolve<Foo>()" is to try to create an instance of  Foo associated with a transient lifetime manager. In my case, this default behavior is dangerous because Foo is disposable and should be registered with another lifetime manager to ensure it is disposed properly. So I would like my Unity container to throw an exception if Foo is not registered.

Developping an custom extension maybe ? I searched the documentation and googled around and I didn't found anything.

Thank you.
Jul 26, 2008 at 11:30 PM
A small extension would be sufficient to make the container throw for any unregistered type; just add a strategy just before the BuildKeyMappingStrategy that checks for a type mapping, and if it's not there, throw. However, if you only want to throw for certain types? That gets a little tricker. I can think of a couple of ways to do it, but they always require some sort of registration in the container for which types are required for registration.

You might be better off building a small extension to do your required registrations in the container. That way, you can just add the extension once and you're all set.

Jul 28, 2008 at 7:13 AM
I don't want to throw for certain types. I will try to create an extention.
Thanks Chris you're doing great job...
Jul 28, 2008 at 5:53 PM
We're still waiting on the events people to post the recording of our Extending Unity webcast, but in the meantime you can grab our demo code from the wiki page. It includes a simple extension example with unit tests which should get you started.