Prevent unregistered concrete type creation?

Jul 5, 2012 at 7:24 PM

It looks like if I ask my container to GetInstance of a concrete type it will try to create one, even if the type hasn't been explicitly registered.  
I'd actually prefer to have an exception thrown or null returned in this case.
Maybe that seems strange, but for my current project I think this will prevent me or others from shooting ourselves in the foot.

Is there a way to achieve this?

Jul 5, 2012 at 7:55 PM
Edited Jul 6, 2012 at 9:12 AM

I will never advise to return null, since it would allow injecting null into constructors, which would be a very bad practice. Preventing unregistered concete types from being created is actually quite simple, and is a matter of registering the ResolveUnregisteredType event and letting it throw an exception. For instance:

container.ResolveUnregisteredType += (s, e) =>
    if (!e.UnregisteredServiceType.IsAbstract)
        throw new Exception(e.UnregisteredServiceType.Name +
            " is a concrete unregistered type.");

You might want to further limit (or expand) the times this exception is thrown, based on the type, for instance to prevent it from resolving umregistered collections (IEnumerable<T>), since the containe will return empty collections. You'll have to play with this a bit to make it suite your situation.

Marked as answer by dot_NET_Junkie on 11/4/2013 at 1:57 AM
Jul 5, 2012 at 8:08 PM

Awesome!  I'm kind of kicking myself for not seeing this before posting.

Once again, I appreciate your quick and helpful response!