Creating an instance using Ninject with additional parameters in the constructor

StuffHappens picture StuffHappens · Feb 9, 2010 · Viewed 54.6k times · Source

I decided to start using Ninject and face an issue. Say I have the following scenario. I have an IService interface and 2 classes implementing this interface. And also I have a class, which has a constructor getting IService and an int. How can I create an instance of this class with Ninject (I dont want to hardwire this int, I want to pass it every time I get an instance)?

Here's some code illustrating the situation:

interface IService
{
    void Func();
}

class StandardService : IService
{
    public void Func()
    {
        Console.WriteLine("Standard");
    }
}

class AlternativeService : IService
{
    public void Func()
    {
        Console.WriteLine("Alternative");
    }
}


class MyClass
{
    public MyClass(IService service, int i)
    {
        this.service = service;
    }

    public void Func()
    {
        service.Func();
    }

    IService service = null;
}
class Program
{
    static void Main(string[] args)
    {
        IKernel kernel = new StandardKernel(new InlineModule(
            x => x.Bind<IService>().To<AlternativeService>(),
            x => x.Bind<MyClass>().ToSelf()));

        IService service = kernel.Get<IService>();

        MyClass m = kernel.Get<MyClass>();
        m.Func();
    }
}

Answer

Ruben Bartelink picture Ruben Bartelink · Feb 9, 2010

The With.ConstructorArgument existed in 1.0 for this purpose. In 2.0, the syntax has changed slightly:- With.Parameters.ConstructorArgument with ninject 2.0

See Inject value into injected dependency for more details and examples of how to use the context, providers and arguments to pass stuff like this around more correctly.

EDIT: As Steven has elected to pretend my comment is irrelevant, I'd best make clear what I'm saying with some examples (for 2.0):

MyClass m = kernel.Get<MyClass>( new ConstructorArgument( "i", 2) );

which to my eyes is very clear and states exactly what's happening.

If you're in a position where you can determine the parameter in a more global way you can register a provider and do it like this:

class MyClassProvider : SimpleProvider<MyClass>
{
    protected override MyClass CreateInstance( IContext context )
    {
        return new MyClass( context.Kernel.Get<IService>(), CalculateINow() );
    }
}

And register it like this:

x => x.Bind<MyClass>().ToProvider( new MyClassProvider() )

NB the CalculateINow() bit is where you'd put in your logic as in the first answer.

Or make it more complex like this:

class MyClassProviderCustom : SimpleProvider<MyClass>
{
    readonly Func<int> _calculateINow;
    public MyClassProviderCustom( Func<int> calculateINow )
    {
        _calculateINow = calculateINow;
    }

    protected override MyClass CreateInstance( IContext context )
    {
        return new MyClass( context.Kernel.Get<IService>(), _calculateINow() );
    }
}

Which you'd register like so:

x => x.Bind<MyClass>().ToProvider( new MyClassProviderCustom( (  ) => new Random( ).Next( 9 ) ) )

UPDATE: Newer mechanisms which exhibit much improved patterns with less boilerplate than the above are embodied in the Ninject.Extensions.Factory extension, see: https://github.com/ninject/ninject.extensions.factory/wiki

As stated earlier, if you need to pass a different parameter each time and you have multiple levels in the dependency graph, you might need to do something like this.

A final consideration is that because you haven't specified a Using<Behavior>, it's going to default to the default as specified/defaulted in the options for the kernel (TransientBehavior in the sample) which might render fact that the factory calculates i on the fly moot [e.g., if it the object was being cached]

Now, to clarify some other points in the comments that are being FUDed and glossed over. Some important things to consider about using DI, be it Ninject or whatever else is to:

  1. Have as much as possible done by constructor injection so you dont need to use container specific attributes and tricks. There's a good blog post on that called Your IoC Container is Showing.

  2. Minimise code going to the container and asking for stuff - otherwise your code is coupled to a) the specific container (which the CSL can minimise) b) the way in which your entire project is laid out. There are good blog posts on that showing that CSL isnt doing what you think it does. This general topic is referred to as Service Location vs Dependency Injection. UPDATE: See http://blog.ploeh.dk/2011/07/28/CompositionRoot.aspx for a detailed and complete rationale.

  3. Minimise use of statics and singletons

  4. Don't assume there is only one [global] container and that it's OK to just demand it whenever you need it like a nice global variable. The correct use of multiple modules and Bind.ToProvider() gives you a structure to manage this. That way each separate subsystem can work on its own and you wont have low-level components being tied to top-level components, etc.

If someone wants to fill in the links to the blogs I'm referring to, I'd appreciate that (they're all already linked from other posts on SO though, so all of this is just duplication UI've introduced with the aim of avoiding the confusion of a misleading answer.)

Now, if only Joel could come in and really set me straight on what's nice syntax and/or the right way to do this!

UPDATE: While this answer is clearly useful from the number of upvotes it's garnered, I'd like to make the following recommendations:

  • The above feels as it's a bit dated and to be honest reflects a lot of incomplete thinking which almost feels embarassing since reading Dependency Injection in .net - Run and buy it now - it's not just about DI, the first half is a complete treatment of all the architecture concerns surrounding it from a man who has spent way too much time here hanging around the dependency injection tag.
  • Go read Mark Seemann's top rated posts here on SO right now - you'll learn valuable techniques from every one