cadrell0
cadrell0

Reputation: 17307

Passing resolving container to a resolved type

I am using Unity.MVC3 and Unity.WCF. Using these packages, you register types with a parent container, then Controllers / Services are created with a child container. Types registered with a HierarchicalLifetimeManager are limited to one instance per request.

I am running into an issue with my classes that take an IUnityContainer as a constructor parameter. I register these like this.

container.RegisterType<IFoo, Foo>(new InjectionConstructor(container));

This causes Foo to be created with an reference to the parent container, not the child container. If I then resolve a type that was registered with a HierarchicalLifetimeManager, I will get a second instance. Additionally, this instance will not be disposed with the child container.

Is there a way to register my types such that they will receive the child container used to resolve them?

Upvotes: 2

Views: 172

Answers (1)

Chris Tavares
Chris Tavares

Reputation: 30401

If an object has a dependency of type IUnityContainer, it'll automatically get injected with the resolving container. You don't need to configure anything, it'll just work.

Upvotes: 2

Related Questions