tharinda dayal

tharinda dayal

  • NA
  • 19
  • 667

Ninject for winforms - how to apply ninject DI for MDI child

May 25 2020 12:37 AM
I am developing desktop base application using c# windows form. Recently I added NInject to my project, it is working good but when i call to child forms from MDI form it's asking constructor parameter of child form because i am using form constructor to pass interface parameter. i don't know how to resolve it.
 
please can any one help me to resolve it. this is my sample project
 
CompositionRoot
  1. public class CompositionRoot  
  2. {  
  3. private static IKernel _ninjectKernel;  
  4. public static void Wire(INinjectModule module)  
  5. {  
  6. _ninjectKernel = new StandardKernel(module);  
  7. }  
  8. public static T Resolve<T>()  
  9. {  
  10. return _ninjectKernel.Get<T>();  
  11. }  
  12. }  
ApplicationModule
  1. public class ApplicationModule : NinjectModule  
  2. {  
  3. public override void Load()  
  4. {  
  5. Bind(typeof(IRepository<>)).To(typeof(GenericRepository<>));  
  6. Bind(typeof(ITest)).To(typeof(TestImpl));  
  7. }  
  8. }  
Program
  1. static class Program  
  2. {  
  3. [STAThread]  
  4. static void Main()  
  5. {  
  6. CompositionRoot.Wire(new ApplicationModule());  
  7. Application.EnableVisualStyles();  
  8. Application.SetCompatibleTextRenderingDefault(false);  
  9. //Application.Run(new Form1());  
  10. Application.Run(CompositionRoot.Resolve<Form1>());  
  11. }  
  12. }  
MDI Form
  1. public partial class Form1 : Form  
  2. {  
  3. private IRepository<Process> _processRepository;  
  4. public Form1(IRepository<Process> productionRepository, ITest test)  
  5. {  
  6. this._processRepository = productionRepository;  
  7. this._test = test;  
  8. InitializeComponent();  
  9. }  
  10. private void button1_Click(object sender, EventArgs e)  
  11. {  
  12. Form2 frm = new *Form2()*;  
  13. frm.Show();  
  14. }  
  15. }  
Child form
  1. public partial class Form2 : Form  
  2. {  
  3. private ITest _test;  
  4. public Form2(ITest test)  
  5. {  
  6. _test = test;  
  7. InitializeComponent();  
  8. }  
  9. private void button1_Click(object sender, EventArgs e)  
  10. {  
  11. var a = _test.DisplayRow();  
  12. MessageBox.Show(a);  
  13. }  
  14. }  
ITest
  1. public interface ITest  
  2. {  
  3. string DisplayRow();  
  4. }  
TestImpl
  1. public class TestImpl : ITest  
  2. {  
  3. public string DisplayRow()  
  4. {  
  5. return "Test service";  
  6. }  
  7. }  
GenericRepository
  1. public class GenericRepository<T> : IRepository<T>  
  2. {  
  3. public override string ToString()  
  4. {  
  5. return "MyRepository with type : " + typeof(T).Name;  
  6. }  
  7. }  
IRepository
  1. public interface IRepository<T>  
  2. {  
  3. }  

Answers (1)