Creating an object after initialization with ninject

I am new to Ninject (and DI in general).

I understand how the kernel loads modules, and the code I have written so far has one line:

myKernel.Get<MyApp>() 

which builds everything I need from the bindings in my module. If there is a requirement to initialize new instances, they take care of the factories that I link to initialize. So far, there have been no Nindger dependencies in factories, just creating objects on demand.

Now I have come to the point that I need to think about creating an object after initialization, and my own factory template does not cut it anymore. This will support the pub / sub interface for (remote) clients. With every new connection to my server, I would like to create new instances of IClient according to the set of bindings defined in the ninject module. Does this mean that the factory that I pass during initialization must have its own kernel (or a link to the main kernel)? Where in this case is the CommonServiceLocator function. Is CSL required?

Before I go too far on dead ends, I thought it was better to ask here how others might approach this problem.

+5
source share
2 answers

Create a factory interface

 public interface IClientFactory { IClient CreateClient(); } 

For Ninject 2.3 see https://github.com/ninject/ninject.extensions.factory and let it be implemented by Ninject by adding the following configuration.

 Bind<IClientFactory>().ToFactory(); 

For 2.2, do the implementation yourself. This implementation is part of the container configuration, not part of your implementations.

 public class ClientFactory: IClientFactory { private IKernel kernel; public ClientFactory(IKernel kernel) { this.kernel = kernel; } public IClient CreateClient() { return this.kernel.Get<IClient>(); } } 
+5
source

It looks like the following factory pattern might satisfy my requirements:

 Bind<Func<IClient>>().ToMethod(ctx => () => ctx.Kernel.Get<ClientImpl>()); 

where I have a constructor of the form:

 SomeCtor(Func<IClient> clientFactory, blah...) 
+1
source

All Articles