Jordi
Jordi

Reputation: 23277

NInject: Resolve constructor injection with two parameters

I've created these interfaces and classes:

interface IInterpreter.
interface IViz.
interface IVizDescriptor.

where,

class IntOne : IInterpreter.

and,

class VizDescOne : IVizDescriptor {
    VizDescOne(string title, Type type, SchemaType schemaType, string desc)
    { }
}

and,

class VizOne : IViz {
    public VizOne (IntOne, IVizDescriptor)
    {
    }
}

I've figured out I'm able to create bindings between IInterpreter and IntOne in order to when I'm requesting for a VizOne, a IntOne is injected to the first parameter constructor.

The problem is that is there no way to create a suitable binding for VizDescOne. VizDescOne's constructor parameters are too dependent of each situation I'm not able to create a binding for it.

Is there some way to provide it manually and resolve the VizOne (IntOne, IVizDescriptor) constructor?

However, IVizDescriptor depends too much of any concrete situation

Upvotes: 1

Views: 723

Answers (1)

YuvShap
YuvShap

Reputation: 3835

You have a lot of options:

  1. You can bind IVizDescriptor to VizDescOne with constructor arguments:

    kernel.Bind<IVizDescriptor>().To<VizDescOne>()
          .WithConstructorArgument("title", "someTitle").WithConstructorArgument("type", typeof(int))...
    
  2. You can bind IVizDescriptor to constant:

    IVizDescriptor vizDescOne = new VizDescOne(...);
    kernel.Bind<IVizDescriptor>().ToConstant(vizDescOne);
    
  3. You can bind IVizDescriptor to method:

    kernel.Bind<IVizDescriptor>().ToMethod(o=> new VizDescOne(...));
    

You can read more about these options and a few more here and here.

As a side note I really suggest you to read @Steven comment and the article that he linked, because if the constructors parameters are do runtime values, you should reconsider your design.

Upvotes: 1

Related Questions