1

I am working on a modular app that is using Unity for its DI container. During startup, the app adds an extension (call it MyUnityExtension) to the unity container.

Now, I am looking to add a new module to the app that uses its own unity container (a child of the parent I would assume) and have that child container have no extensions defined.

  1. If I create a child container of the parent container, would the child container also inherit MyUnityExtension? I searched and found some old info indicating that it would not but wanted to make sure.

  2. Unity has a feature where even if classes are not registered, you can request an instance of a concrete type that depends on those classes, and Unity will figure out how to create them and give you instances (found that info here). In my new module I would like Unity to only check the child container I created earlier when doing any resolving and not consider the parent container. I can't see a way to hook into this process as Unity is doing the resolving on its own (since the class has not been registered) and I don't know how the process is changed when child containers exist.

I am new to unity so not sure if this is possible.

Flack
  • 5,727
  • 14
  • 69
  • 104
  • 1
    If you do not want your parent registrations used, why are you using a child container (`CreateChildContainer()`) instead of just using a new container (`new UnityContainer()`)? What benefit of using a child container are you looking for? – Lukazoid Mar 31 '14 at 11:55

3 Answers3

1

Ok so firstoff here is a very good Tutorial for Unity.

Then
AFAIK when you create a child container this is the exact behavior but if you want to be sure there is a Method defined in IUnityContainer called RemoveAllExtensions. This method removes ALL Extensions the default ones too. So after that you would have to configure the container with your Extensions and maybe the default ones that you want.
Which also is your second point. With Extensions you can basically insert any logic into the UnitContainer lifecycle eg. handle resolveing differently etc. If you want to know more about Extensions here are some links:

Hope that gets you on the right Track ;)

Community
  • 1
  • 1
D4rth B4n3
  • 1,268
  • 2
  • 17
  • 26
0

It depends on the which object lifecycle you are using, suppose if you are using heirarchicallifetimemanager then child container will use the same the object instead of creating new one where as if you are using ContainerControlledLifetimeManager then the object won't be shared between parent and child.

0
var childContainer = unity.CreateChildContainer();

childContainer.RegisterType<IExtended, ExtendedImp>();

var yourClass = childContainer.Resolve<SomeClassToResolve>();
Amir Touitou
  • 3,141
  • 1
  • 35
  • 31