Resolve resolving unregistered objects

Aug 16, 2011 at 7:12 AM

I'm sure this is known behavior - probably even a feature, but it surprised me a bit, particularly since I cannot find it mentioned in the documentation.

UnityContainer.Resolve seems to resolve (construct?) any classes that it can, even if they are not registered with the container:

void Main()
	var uc = new UnityContainer();
	var b = uc.Resolve<Bar>(); // expected ResolutionFailedException
	b.Name.Dump();  // => "Bar" - or at least a NRE on b.

	var f = uc.Resolve<Foo>("secondary"); // expected ResolutionFailedException because 'secondary' is not registered
	f.Name.Dump(); // => "So a horse..."

	var ex = uc.Resolve<EventArgs>(); // same - no RFE

// Define other methods and classes here 
class Bar { public string Name = "Bar"; }
class Foo {
	Bar b;
	public Foo(Bar aBar) {
		b = aBar;
	public string Name { 
		get { 
			return string.Format("So a horse walks into a {0}...", b.Name);

Of course, uc.IsRegistered<Bar>() and even uc.IsRegistered<Foo>("secondary") report false.

Good design would recommend that we code against interfaces (in which case RFEs are thrown as expected), but given that is not always possible (legacy code), and given the performance issues we saw with IsRegistered, what would you recommend a developer does to ensure Unity will not return/construct objects that are not registered with the container?

Aug 16, 2011 at 9:36 AM


Actually, this behavior is documented here:

"You can use the Unity container to generate instances of any object that has a public constructor (in other words, objects that you can create using the new operator), without registering a mapping for that type with the container. When you call the Resolve method and specify the default instance of a type that is not registered, the container simply generates and returns an instance of that type. However, the only time that this is realistically practical is when the object you are generating contains dependency attributes that the container will use to inject dependent objects into the requested object."

Hope this helps.


Noel Angelo Bolasoc
Global Technologies and Solutions
Avanade, Inc.
Contact Us