1

I have a class like this:

public class MyClass
{
    public MyClass(IService service)
    {
        this.Service = service;
        this.Dependency = new Dependency(service);
    }
}

I want to move the new Dependency() call to the constructor.

public class MyClass
{
    public MyClass(IService service, IDependency dependency)
    {
        this.Service = service;
        this.Dependency = dependency;
    }
}

I can't work out how to bind it so that the IDependency is created with the service constructor argument.

Bind<IDependency>()
  .To<Dependency>()
    .WithConstructorArgument("service", ctx => ctx.???); // How do I do this?
shamp00
  • 11,106
  • 4
  • 38
  • 81
  • Dupe of the same question you asked a few hours before: http://stackoverflow.com/questions/19253827/how-do-i-bind-a-class-which-takes-its-parent-class-in-the-constructor-with-ninje/19253923#comment28502654_19253923 – Killnine Oct 10 '13 at 16:35
  • @Killnine they are similar but different questions. The other one was about `this`. – shamp00 Oct 11 '13 at 16:18

1 Answers1

1

So you want to have the same instance of IService to be ctor-injected into multiple objects. There are 2ways to achieve this:

  • scoped binding of IService: .InSingletonScope(), InCallScope(), InNamedScope("xyz") etc. (see https://github.com/ninject/ninject/wiki/Object-Scopes)
  • implement and use a factory to create MyClass. The factory then 1st instantiates IService (IResolutionRoot.Get<IService>();), and then instantiates and returns MyClass using a ctor argument, p.Ex. like this: IResolutionRoot.Get<MyClass>(new ConstructorArgument("service", service);

You could also bind IMyClass .ToProvider() and have the provider implement the factory logic to get rid of the extra factory call. But this makes the actual target class binding hard in case u want to bind an interface to multiple classes (with conditions or otherwise). See How to use a Provider in Ninject

Creating an instance using Ninject with additional parameters in the constructor could also be interesting for you.

Community
  • 1
  • 1
BatteryBackupUnit
  • 12,934
  • 1
  • 42
  • 68