我想知道如何使用Ninject将对象注入为已创建该对象的依赖项。我在主窗口的WPF Window_Loaded方法中有以下代码:
IKernel kernel = new StandardKernel();
kernel.Bind<ITeleStore>().To<TeleStore>();
kernel.Bind<ITreeViewModel>().To<TreeViewModel>();
var tst = kernel.Get<TeleStore>();
// rootnode already exists and is obtained from the telestore component
TstTreeNode rootNode = tst.GetRootNode();
// how do I use ninject to inject rootnode?
ITreeViewModel treeViewModel = new TreeViewModel(rootNode);
base.DataContext = treeViewModel;
答案 0 :(得分:2)
您可以将根节点作为参数传递给请求!简单到以下
public interfacte ITreeViewModel
{
public TstTreeNode TestNode {get;}
........
// Other members
}
// Sample Class
public class TreeViewModel : ITreeViewModel
{
public TreeViewModel(TstTreeNode node) {
TestNode = node;
}
// Implemented from interface
public TstTreeNode TestNode {get; private set;}
}
// Your code
IKernel kernel = new StandardKernel();
kernel.Bind<ITeleStore>().To<TeleStore>();
kernel.Bind<ITreeViewModel>().To<TreeViewModel>();
var tst = kernel.Get<TeleStore>();
// rootnode already exists and is obtained from the telestore component
TstTreeNode rootNode = tst.GetRootNode();
// how do I use ninject to inject rootnode?
ITreeViewModel treeViewModel = kernel.Get<TreeViewModel>(new ConstructorArgument("node", rootNode));
玩得开心!
答案 1 :(得分:0)
您可以尝试使用property-injection在TreeViewModel类中设置“TstTreeNode”值。以下是示例代码: -
public interfacte ITreeViewModel
{
public TstTreeNode TestNode {get;set;}
........
// Other members
}
// Sample Class
public class TreeViewModel : ITreeViewModel
{
public TreeViewModel() {}
// Implemented from interface
public TstTreeNode TestNode {get;set;}
}
// Your code
IKernel kernel = new StandardKernel();
kernel.Bind<ITeleStore>().To<TeleStore>();
kernel.Bind<ITreeViewModel>().To<TreeViewModel>();
var tst = kernel.Get<TeleStore>();
// rootnode already exists and is obtained from the telestore component
TstTreeNode rootNode = tst.GetRootNode();
// how do I use ninject to inject rootnode?
ITreeViewModel treeViewModel = kernel.Get<TreeViewModel>();
// Property Injection
treeViewModel.TestNode = rootNode
base.DataContext = treeViewModel;