How to use a provider in Ninject

I have the following code

public class Something { [Inject] public Configuration config {get;set;} //singleton [Inject] public Provider<WindowHandler> windowsProvider { get; set; } //NOT singleton public void Search(string text) { WindowHandler handler = windowsProvider.Create(xxxxxx); //use the new handler that was created } } 

but it seems that the provider is taking IContext, where I put xxxxxx. You should not use IContext from the moment I booted up and created Something.cs from the kernel. Where there is no Create method on the Provider ??? (I come from the point of view of Guice land, where it will be encoded as described above).

so the question is: How do I do it right?

thanks dean

+6
source share
2 answers

It seems you are trying to use a provider as a factory in your code.

A Ninject-based provider is a factory provided by Ninject to create custom-created objects. Therefore, it gets a resolving context that can be used to create different instances, depending on where the injected instance is.

 public class FooProvider : Provider<IFoo> { public override IFoo CreateInstance(IContext ctx) { // add here your special IFoo creation code return new Foo(); } } kernel.Bind<IFoo>().ToProvider<FooProvider>(); 

What you need is a factory in the encoder that creates the WindowHandler instance. Therefore, create an interface to create an instance as follows:

 public interface IWindowHandlerFactory { WindowHandler Create(); } Bind<IWindowHandlerFactory>().ToFactory(); 

Alternatively, you can insert Func<WindowHandler> without adding a configuration. But this, in my opinion, is less significant.

NOTE. This requires Ninject.Extensions.Factory, available as a preview release of 3.0.0-rc2 from Nuget.

See also: http://www.planetgeek.ch/2011/12/31/ninject-extensions-factory-introduction/

+12
source

Well, my final decision was to trick in ninject 2.0 with the following code ...

  var windowFactory = kernel.Get<IEWindowFactory>(); var tabFactory = kernel.Get<IETabFactory>(); windowFactory.Kernel = kernel; tabFactory.Kernel = kernel; 

and in the list of bindings

 Bind<IEWindowFactory>().ToSelf().InSingletonScope(); Bind<IETabFactory>().ToSelf().InSingletonScope(); 

and after that I just run my application

 var main = kernel.Get<MainForm>(); main.Start(); 

and, of course, factories are introduced where I need them, in the hierarchy of this MainForm.

therefore, I manually installed the kernel at startup, and then when I load my application, naturally, these factories are fields in classes with [Ninject] annotation, and therefore they can create objects. not the cleanest until we get 3.0, but it works (and I hate extra factory classes, I have to write code, but ok).

+1
source

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


All Articles