How are instances resolved when child containers are used?

in the code snippet below, we have a root container and one child container. In the child container, registration is performed for Person, which depends on the INameProviderone defined in the root container. INameProviderin turn depends on IInfoProviderwhich has registration in both containers.

When a child container is prompted to allow an instance Person, the mechanism uses the root container to resolve the instance INameProvider(as expected), but also to allow the instance IInfoProvider. I expect that the registration for IInfoProviderin the child container will override the registration in the root container.

WindsorContainer rootContainer = new WindsorContainer();

// register components for root container
rootContainer.Register(
   Castle.MicroKernel.Registration.Component.For<IInfoProvider>().
      ImplementedBy<InfoProvider>().
      LifeStyle.Transient);
rootContainer.Register(
   Castle.MicroKernel.Registration.Component.For<INameProvider>().
      ImplementedBy<BobNameProvider>().
      LifeStyle.Transient);

// create child container
WindsorContainer childContainer = new WindsorContainer();
rootContainer.AddChildContainer(childContainer);

// register components for child container
childContainer.Register(
   Castle.MicroKernel.Registration.Component.For<Person>().
      LifeStyle.Transient);
childContainer.Register(
   Castle.MicroKernel.Registration.Component.For<INameProvider>().
      ImplementedBy<JimNameProvider>().
      LifeStyle.Transient);

var person = childContainer.Resolve<Person>();

Debug.Assert(person.ToString() == "Jim"); // <- fails, because person.ToString is "Bob"

, INameProvider ( ), IInfoProvider. , .

var np = childContainer.Resolve<INameProvider>();
np.ToString() // <-- equals "Jim"

- , IInfoProvider ?

, , ?

# 1 , , . - MVC, , , . , ( ), MVC . , Container.GetChildContainer . , , , .

+3

Source: https://habr.com/ru/post/1776314/


All Articles