Don't understand ninject and injection

I have a class that contains my actions (any logic):

public class socActions { public void Choose(int elem) { switch(elem) ... CalcA(elem) || CalcB(elem) ... } public void CalcA() { } public void CalcB() { } public void CalcC() { } } 

So, in my program, when I get the elem value, I use it like:

 (new socActions()).Choose(elem_val); 

Okey, but in the methods of the socActions class, I would like to have a connection to my repository or make any other dependency injection.

  • If I add the IRepositoryMy construct to the constructor, I would not be able to create classes, as indicated above, bcz is now its constructor with the IRepositoryMy argument.
  • If I try to inject into a field, this does not work (property = null).
  • If I try to inject in methods (CalcA, CalcB), it does not work either.

How should I really accomplish this task (enter a class, such as a repository)? Do not want to mark everything in my application as static :(

WinForms, C #, Ninject 3

Edit:

 public class socActions { [Inject] public IGridProcessor _GridProcessor { private get; set; } 

therefore, in the method its value is null:

 public void UpdateInfo(...) { ... this._GridProcessor.Refresh(); } 

In other classes, where I insert an IGridProcessor into a class in the constructor, everything is fine. In Program.cs:

  static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var kernel = new StandardKernel(new TwttModule()); var form = kernel.Get<Main>(); Application.Run(form); } public class TwttModule : NinjectModule { public override void Load() { Bind<IGridProcessor>().To<GridProcessor>(); } } public static class AnyClass { public static void Act() { .... (new socActions()).Choose(elem_val); } } 

How do I add an IGridProcessor to socActions?

+4
source share
1 answer

When using constructor installation, you do not create your classes directly, but specify ninject for the instance. Based on how you configured ninject, you get a new instance or singleton instance, etc.

From your documents:

 Samurai warrior = kernel.Get<Samurai>(); 
0
source

Source: https://habr.com/ru/post/1447205/


All Articles