Mir*_*rek 6 c# wpf ninject .net-4.0
我在WPF中迷失了Ninject.
我在App.xaml中初始化它,但MainWindow.xaml中的ITest属性(即使使用InjectAttribute)也没有得到解析并保持为null.
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
IKernel kernel = new StandardKernel();
kernel.Bind<ITest, Test>();
base.OnStartup(e);
}
}
Run Code Online (Sandbox Code Playgroud)
我用Google搜索了一下,发现它不起作用.在试图找到一个解决方案时,我最终创建了IMainWindow,只有"void Show();" 并将其添加到MainWindow.
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
IKernel kernel = new StandardKernel();
kernel.Bind<ITest, Test>();
kernel.Bind<IMainWindow, MySolution.MainWindow>();
kernel.Get<IMainWindow>().Show();
base.OnStartup(e);
}
}
Run Code Online (Sandbox Code Playgroud)
为此,我在.Get的行上得到NullReferenceException
我也试过这个:
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
IKernel kernel = new StandardKernel();
kernel.Bind<ITest, Test>();
MainWindow = new MySolution.MainWindow(kernel);
//then kernel.Inject(this); in the MainWindow constructor
MainWindow.Show();
base.OnStartup(e);
}
}
Run Code Online (Sandbox Code Playgroud)
现在我在MainWindow的.Inject行中得到一个NullReferenceException.
我找到了另一种不同的解决方案,但它们看起来很重量级,我放弃了测试所有这些并尝试哪种方法有效.
有什么帮助吗?
您没有正确注册您的类型,这就是第二个示例抛出execption的原因.正确的语法是:kernel.Bind<SomeInterface>().To<SomeImplementation>()
所以正确用法:
protected override void OnStartup(StartupEventArgs e)
{
IKernel kernel = new StandardKernel();
kernel.Bind<ITest>().To<Test>();
kernel.Bind<IMainWindow>().To<MainWindow>();
var mainWindow = kernel.Get<IMainWindow>();
mainWindow.Show();
base.OnStartup(e);
}
Run Code Online (Sandbox Code Playgroud)
您需要使用以下[Inject]属性标记您的属性:
public partial class MainWindow : Window, IMainWindow
{
public MainWindow()
{
InitializeComponent();
}
[Inject]
public ITest Test { get; set; }
}
public interface IMainWindow
{
void Show();
}
Run Code Online (Sandbox Code Playgroud)