注入已经用Ninject创建的依赖项
本文关键字:依赖 创建 Ninject 注入 | 更新日期: 2023-09-27 17:50:22
我想知道如何使用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;
您可以将根节点作为参数传递给请求!简单到以下
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));
玩得开心!
你可以尝试使用属性注入来设置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;