我在我的应用程序中使用Ninject以及Factory和NamedScope扩展。我要创建以下层次结构:
这是我当前的代码:
public interface IChildFactory
{
ScopedChild Create();
}
public interface IGrandChildFactory
{
ScopedGrandChild Create();
}
public class ScopedParent
{
private static int _nextId;
public IChildFactory ChildFactory { get; }
public IList<ScopedChild> Children { get; } = new List<ScopedChild>();
public int Id { get; set; }
public ScopedParent(IChildFactory childFactory)
{
ChildFactory = childFactory;
Id = Interlocked.Increment(ref _nextId);
}
public void GenerateKids()
{
for (int i = 0; i < 5; i++)
{
var kid = ChildFactory.Create();
Children.Add(kid);
kid.GenerateKids();
}
}
}
并且:
public class ScopedChild
{
public IGrandChildFactory GrandChildFactory { get; }
private static int _nextId;
public int Id { get; set; }
public IList<ScopedGrandChild> Grandchildren { get; } = new List<ScopedGrandChild>();
public ScopedChild(IGrandChildFactory grandChildFactory)
{
GrandChildFactory = grandChildFactory;
Id = Interlocked.Increment(ref _nextId);
}
public void GenerateKids()
{
for (int i = 0; i < 3; i++)
{
Grandchildren.Add(GrandChildFactory.Create());
}
}
}
public class ScopedGrandChild
{
public ScopedParent ScopedParent { get; }
public ScopedChild ScopedChild { get; }
public ScopedGrandChild(ScopedParent scopedParent, ScopedChild scopedChild)
{
ScopedParent = scopedParent;
ScopedChild = scopedChild;
}
}
在这篇文章中,我遇到了一个注入根对象的建议:Ninject: How to access root object of NamedScope from factory 但是我无法将单独的ScopedChild实例注入适当的ScopedGrandChild类。
最终我想打以下电话:
var parent = kernel.Get<ScopedParent>();
var parent2 = kernel.Get<ScopedParent>();
// call subsequent generate kids
parent.GenerateKids();
parent2.GenerateKids();
并接收初始化的完整层次结构。