How to register types in the main container, but allow in the child container?

I have a unity container and use RegisterType to register the next repository and developer using the ContainerControlledLifetimeManager .

 public interface IPersonRepository { Person GetByID(ObjectSpace objectSpace, int id); } 

Using this template, I can have several threads (this is a web application) using the same repository instance at the same time, despite the fact that each thread uses a different ObjectSpace (which is a local cache + mechanism for selecting objects from the database + units of work etc.). But it makes me feel "dirty" and not kind :-)

I would like:

 public interface IPersonRepository { Person GetByID(int id); } 

To do this, I need to create a child container and use RegisterInstance to register my ObjectSpace . This will work fine if I, too:

  • Register IPersonRepository in the child container instead
  • Change the time manager to TransientLifetimeManager

I don’t want to do that either. (1) It would just be too much work, I want to register once in the parent container, and then no more. (2) It will work, but if there are many dependencies, then all of them should also be temporary, and this will lead to the creation of many instances every time I need a repository.

So my question is: is there a way to register the type in the parent, but so that the container resource instance is resolved and stored in the child container instead of the parent container? Maybe there is a way to use a custom life manager or something like that?

I would like to achieve this:

 UnityContainer unityContainer = new UnityContainer(); //Might be a custom manager or something unityContainer.RegisterType<IPersonRepository, PersonRepository> (new ContainerControlledLifetimeManager()); using (var childContainer = unityContainer.CreateChildContainer()) { childContainer.RegisterInstance<ObjectSpace>(new MyObjectSpace()); //01 Resolves a new instance inside the child container var repository = childContainer.Resolve<IPersonRepository>(); //02 resolves same instance as 01 repository = childContainer.Resolve<IPersonRepository>(); } using (var childContainer = unityContainer.CreateChildContainer()) { childContainer.RegisterInstance<ObjectSpace>(new MyObjectSpace()); //03 Resolves a new instance inside the child container var repository = childContainer.Resolve<IPersonRepository>(); //04 resolves same instance as 03 repository = childContainer.Resolve<IPersonRepository>(); //Resolves the same instance } 
+4
source share
1 answer

Since asking a question, a new HierarchicalLifetimeManager added to Unity, this should be used when registering a type.

0
source

All Articles