Dependency Injection in WinForms using Ninject and Entity Framework

假如想象 提交于 2019-12-02 14:32:24

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!