Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a Provider in Ninject

Tags:

c#

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 the Provider takes an IContext where I put xxxxxx. Shouldn't the IContext from when I bootstrapped and created Something.cs from the kernel be used. Where is the no parameter Create method on the Provider??? (I am coming from Guice land point of view where it would be coded like above).

so the question is How do I do this correctly?

thanks, Dean

like image 427
Dean Hiller Avatar asked Jan 03 '12 17:01

Dean Hiller


People also ask

How to implement Dependency Injection in c# using Ninject?

Step 1: We are creating an instance of Class StandardKernel. Step 2: Then we will load the Kernel. Step 3: Get the instance of the specific service that we want to inject. Step 4: Then inject the dependency.

What is a ninject module?

The Ninject modules are the tools used to register the various types with the IoC container. The advantage is that these modules are then kept in their own classes. This allows you to put different tiers/services in their own modules.

Why Ninject is used?

Ninject is a lightweight dependency injection framework for . NET applications. It helps you split your application into a collection of loosely-coupled, highly-cohesive pieces, and then glue them back together in a flexible manner.


1 Answers

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

A provider in Ninject terms is a factory that is given to Ninject to create specially created objects. Therefore it gets the resolving context which can be used to create different instances depending where the instance in injected into.

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 want is a factory in your coder that creates an instance of WindowHandler. Therefore create an interface to create the instance like this:

public interface IWindowHandlerFactory
{
    WindowHandler Create();
}

Bind<IWindowHandlerFactory>().ToFactory();

Alternatively you can inject Func<WindowHandler> without adding a configuration. But this is less meaningful in my opinion.

NOTE: All this requires Ninject.Extensions.Factory available as prerelease 3.0.0-rc2 from Nuget.

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

like image 174
Remo Gloor Avatar answered Sep 19 '22 13:09

Remo Gloor