Minimum Example:
Install the package by Nuget or Package Manager Console
Install-Package Ninject
Create a class that is responsible for resolving dependencies:
FormModule
using Ninject.Modules;
public class FormModule : NinjectModule
{
public override void Load()
{
Bind<IMount>().To<Mount>();
}
public static FormModule Create()
{
return new FormModule();
}
}
In the Load
method call Bind
to class configuration and place all classes that will be used in your project and which are dependencies of other forms.
Create a class that will be responsible for instantiating the Form
and consequently the their dependencies :
FormResolve
using Ninject;
using Ninject.Modules;
public class FormResolve
{
private static IKernel _ninjectKernel;
public static void Wire(INinjectModule module)
{
_ninjectKernel = new StandardKernel(module);
}
public static T Resolve<T>()
{
return _ninjectKernel.Get<T>();
}
}
In the file Program.cs
set as follows:
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
FormResolve.Wire(FormModule.Create());
Application.Run(FormResolve.Resolve<Form1>());
}
}
}
With these two classes and the configuration made in Program.cs
is ready to resolve dependencies.
Example: Form1
using Ninject;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
private IMount Mount { get; set; }
[Inject()]
public Form1(IMount mount)
{
InitializeComponent();
Mount = mount;
}
private void Form1_Load(object sender, System.EventArgs e)
{
label1.Text = Mount?.GetDateTime().ToLongDateString();
}
private void button1_Click(object sender, System.EventArgs e)
{
Form2 frm = FormResolve.Resolve<Form2>();
frm.ShowDialog();
}
}
}
To call form2
or any form
follow the example of the button below where form1
calls form2
:
private void button1_Click(object sender, System.EventArgs e)
{
Form2 frm = FormResolve.Resolve<Form2>();
frm.ShowDialog();
}
References: