All containers support child containers. 

Example of creating a child container:

//Create container.
var injector = new MugenInjector();
//Create child container.
var child = injector.CreateChild();
if (child.GetRoot() == injector)
    Console.WriteLine("Is always true");
if (injector.ChildInjectors.Contains(child))
    Console.WriteLine("Is always true");

Service can be activated in parent container or child.

Example for activate in parent:

var injector = new MugenInjector();
//If not find binding, resolve in parent(use parent binding).
injector.Settings.UseParentForResolve = true;
var obj1 = new SomeClass1 { Id = Guid.NewGuid() };
var obj2 = new SomeClass1 { Id = Guid.NewGuid() };
Debug.Assert(obj1.Id != obj2.Id);

//Bind two object in parent container.
injector.Bind<ISomeInterface>().To<SomeClass>();
injector.Bind<ISomeInterface1>().To<SomeClass1>();
//Get instance of SomeClass from parent container.
var someClass = injector.Get<ISomeInterface>() as SomeClass;

//Create child injector
var child = injector.CreateChild() as MugenInjector;
//Bind ISomeInterface1 to const object.
child.Bind<ISomeInterface1>().ToConstant(obj2);

//Get instance of SomeClass from child container.
var someClassChild = child.Get<ISomeInterface>() as SomeClass;

//ISomeInterface1 get from parent container not use constant binding in child.
Debug.Assert(someClass.SomeInterface1.Id == someClassChild.SomeInterface1.Id);

Example for activate in child:

var injector = new MugenInjector();

//If not find binding, resolve in child(use child bindings).
injector.Settings.UseParentForResolve = false;
var obj1 = new SomeClass1() { Id = Guid.NewGuid() };
var obj2 = new SomeClass1() { Id = Guid.NewGuid() };
Debug.Assert(obj1.Id != obj2.Id);

//Bind two object in parent container.
injector.Bind<ISomeInterface>().To<SomeClass>();
injector.Bind<ISomeInterface1>().To<SomeClass1>();
//Get instance of SomeClass from parent container.
var someClass = injector.Get<ISomeInterface>() as SomeClass;

//Create child injector
var child = injector.CreateChild() as MugenInjector;
//Bind ISomeInterface1 to const object.
child.Bind<ISomeInterface1>().ToConstant(obj2);

//Get instance of SomeClass from child container.
var someClassChild = child.Get<ISomeInterface>() as SomeClass;

//ISomeInterface1 get from child container it's constant binding obj2.
Debug.Assert(someClass.SomeInterface1.Id != someClassChild.SomeInterface1.Id);

Last edited Apr 5, 2012 at 6:00 PM by VVS0205, version 8

Comments

No comments yet.