Question

I have a troublesome Windows service (see this question), and I am considering creating a custom scope factory to generate a new scope each time the service ticks.

I plan to inject the kernel into this factory, so that it can return a new scope for the service on every tick and destroy / release the scope after each tick.

To facilitate this, I plan to added this to my RegisterServices() method:

kernel.Bind<IKernel>().ToConstant(kernel);

And my custom scope factory would look like this:

public class CustomScopeFactory : ICustomScopeFactory
{
    private readonly IKernel kernel;

    public CustomScopeFactory(IKernel kernel)
    {
        this.kernel = kernel;
    }

    public ICustomScope CreateScope()
    {
        return kernel.Get<ICustomScope>();
    }

    public void DisposeScope(ICustomScope scope)
    {
        kernel.Release(scope);
    }
}

I wouldn’t usually consider registering the kernel in the kernel or injecting it, but in this scenario I think it is a valid use case.

So, is it ok to register the Ninject kernel in the kernel itself? Any thoughts or alternatives would be appreciated.

Was it helpful?

Solution 2

So, is it ok to register the Ninject kernel in the kernel itself?

Yes, there is no problem with this. Injecting the kernel into classes is fine, as long as those classes are located in the Composition Root. Injecting the kernel into classes that are located outside the Composition Root leads to the Service Locator anti-pattern, while injecting into classes that are placed inside the Composition root is merely mechanics.

OTHER TIPS

You don't need to register the IKernel. It is automatically injected for any container-created classes that have a IKernel dependency (constructor, field or property).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top