Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF app with Ninject

I'm lost with Ninject in WPF.

I'm initializing it in App.xaml but the ITest property in MainWindow.xaml (even with the InjectAttribute) is not getting resolved and remains null.

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {    
        IKernel kernel = new StandardKernel();
        kernel.Bind<ITest, Test>();
        base.OnStartup(e);
    }
}

I googled a bit and found out that it doesn't work that way. In trying to find a solution, I ended up with creating IMainWindow with nothing else but "void Show();" and adding it to the 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);
    }
}

For this, I'm getting a NullReferenceException on the line with .Get

I also tried this:

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);
    }
}

Now I'm getting a NullReferenceException at the .Inject line in the MainWindow.

I found another various solutions but they seemed heavyweight and I gave up testing all of them and trying which one works.

Any help please?

like image 312
Mirek Avatar asked Nov 17 '12 15:11

Mirek


1 Answers

You are not registering your types correctly that is why the second example throws an execption. The correct syntax is: kernel.Bind<SomeInterface>().To<SomeImplementation>()

So the correct usage:

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);
}

And you need to mark your property with the [Inject] attribute:

public partial class MainWindow : Window, IMainWindow
{
    public MainWindow()
    {
        InitializeComponent();
    }

    [Inject]
    public ITest Test { get; set; }
}

public interface IMainWindow
{
    void Show();
}
like image 88
nemesv Avatar answered Sep 28 '22 08:09

nemesv