I'm trying to inject dependencies into a heirarchy with Ninject and I have a question about scoping in deferred injection. I have a basic hierarchical structure containing a parent and a child. The child gets injected into the parent and they both get injected with a "Coat of Arms" property:
public class Parent
{
[Inject]
public Child Child { get; set; }
[Inject]
public CoatOfArms CoatOfArms { get; set; }
}
public class Child
{
[Inject]
public CoatOfArms CoatOfArms { get; set; }
}
public class CoatOfArms
{
}
Since they're in the same family they should both get the same coat of arms, so I set up my bindings to scope them to the CoastOfArms in the parent request:
public class FamilyModule : NinjectModule
{
public override void Load()
{
Bind<Parent>().ToSelf();
Bind<Child>().ToSelf();
Bind<CoatOfArms>().ToSelf().InScope(ctx =>
{
var request = ctx.Request;
if (typeof(Parent).IsAssignableFrom(request.Service))
return request;
while ((request = request.ParentRequest) != null)
if (typeof(Parent).IsAssignableFrom(request.Service))
return request;
return new object();
});
}
}
This all works fine, but let's say I want to change it slightly so that the child is injected later, well after the parent has been injected. I remove the Inject attribute on the Child property, inject the kernel and use it to inject the child in a method:
[Inject]
public IKernel Kernel { get; set; }
public Child Child { get; set; }
public void InjectChild()
{
this.Child = this.Kernel.Get<Child>();
}
This breaks because it's a completely new request and the walk up the request tree stops with this request. I could manually pass in the CoatOfArms as a property but then I would have to remember to do that everywhere else in the code that tries to create a child object. Also the child class may have children and grandchildren of its own etc so I would wind up having to manually pass parameters all down the hierarchy chain again thus losing all the benefits of dependency injection scoping to begin with.
Is there a way to create my child object and somehow link the request to the parent request so that scoping works as if the child had been injected at the same time as the parent?