vendredi 20 octobre 2017

Ninject passing reference in constructor

I am a noob with dependency Injections, I followed the tutorial and refactored my code to use Ninject. Here it is what I have (simplified). Bindings.cs

 public class Bindings : NinjectModule
    {
        public override void Load()
        {
            Bind<IConnectionToModbusCreator>().To<ConnectionToModbusCreator>();
            Bind<IInputProcessor>().To<InputProcessor>();
}}

Program.cs ;

static class Program
    {
        [STAThread]
        static void Main()
        {
            var kernel = new StandardKernel();
            kernel.Load(Assembly.GetExecutingAssembly());
            var InputProcessor = kernel.Get<IInputProcessor>();

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1(InputProcessor));
}

This start a form, the user by clicking a button start the program, here is the Form1:

    public partial class Form1 : Form
    {
        private readonly IInputProcessor _inputProcessor;

        public Form1(IInputProcessor inputProcessor)
        {            _inputProcessor = inputProcessor;
            InitializeComponent();
        }
        private void Test_Click_1(object sender, EventArgs e)
        {
  ISequenceController sequenceController = new SequenceController( _inputProcessor)
            sequenceController.StartSequence();
        }

My problem is:

Is this the best way? I am worried by all the references I have to pass in the constructors, I tried to use a class Container which keeps variables with the objects instantiated and use them as properties but I cannot find sich method in any Ninject manual.

Aucun commentaire:

Enregistrer un commentaire