Dependency Injection in WinForms using Ninject and Entity Framework

后端 未结 1 1700
[愿得一人]
[愿得一人] 2021-01-30 04:26

I am currently working on a project where we are converting our old DataSet, Stored Procedure WinForm application to use Entity Framework so new websites can access the same obj

相关标签:
1条回答
  • 2021-01-30 05:26

    You create composition root as one entry point for your resolutions. You pass INjectModule as a parameter so that you can configure it it tests differently. One of the benefits of Composition Root is that not all of your assemblies will depend on NInject and you will have one single point to change resolution logic. It is really a cool pattern, when you might change IoC container or introduce some dynamic interception in future.

    public class CompositionRoot
    {
        private static IKernel _ninjectKernel;
    
        public static void Wire(INinjectModule module)
        {
            _ninjectKernel = new StandardKernel(module);
        }
    
        public static T Resolve<T>()
        {
            return _ninjectKernel.Get<T>();
        }
    }
    

    Your module would look like this

    public class ApplicationModule : NinjectModule
    {
        public override void Load()
        {
            Bind(typeof(IRepository<>)).To(typeof(GenericRepository<>));
        }
    }
    

    In main method you pass ApplicationModule as a parameter and resolve Form1 and start it.

    [STAThread]
    static void Main()
    {
        CompositionRoot.Wire(new ApplicationModule());
    
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
    
        Application.Run(CompositionRoot.Resolve<Form1>());
    }
    

    In Form1 constructor you pass required repository with specific closed generic parameters

    public partial class Form1 : Form
    {
        private IRepository<Process> _processRepository;
    
        public Form1(IRepository<Process> productionRepository)
        {
            this._processRepository = productionRepository;        
            InitializeComponent();
        }  
    
        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show(_processRepository.ToString());
        }
    }
    

    Your repositories could be very complex, but I won't add any functionality to them, instead of ToString() method so that we could see if a dependency was resolved correctly. Note there are no attributes whatsoever on repositories.

    public interface IRepository<T>
    {
    }
    
    public class GenericRepository<T> : IRepository<T>
    {
        public override string ToString()
        {
            return "MyRepository with type : "+typeof(T).Name;
        }
    }
    

    Now when you run your application, you will see, that all has wired up and message box shows an enclosed type as Process

    enter image description here

    0 讨论(0)
提交回复
热议问题