2

Given the following ASP.NET Core controller :

public class MyController : Controller {
    public MyController(IDependency dependency) { this.dependency = dependency; }
}

public interface IDependency;

public class DependencyImplementation : IDependency {
    public DependencyImplementation(Controller controller) { ... }
}

I want MyController to have a new instance of DependencyImplementation injected, constructed with the controller it's being passed to. Ideally using Ninject.

The non-IoC version would be:

public class MyController : Controller {
    public MyController() { this.dependency = new DependencyImplementation(this); }
}
Jan Muncinsky
  • 4,282
  • 4
  • 22
  • 40
DaveD
  • 2,196
  • 1
  • 23
  • 33
  • this should help https://stackoverflow.com/a/46747913/1236044 – jbl Nov 15 '17 at 08:40
  • Your code causes a Dependency cycle. Dependency cycles are bad and should typically be prevented. So please explain _why_ you need that `Controller` injected into the dependency. Preferably using some code. – Steven Nov 15 '17 at 10:44
  • I think that `Dependency Injection` book provides solution for such kind of situations, yet uses the `this` hack. – VMAtm Nov 22 '17 at 00:37

1 Answers1

3

This would cause circular dependency. Only idea I have is to introduce factory:

public interface IDependencyFactory
{
    IDependency Create(Controller controller);
}

public class MyController : Controller
{
    private IDependency dependency;

    public MyController(IDependencyFactory dependencyFactory)
    {
        this.dependency = dependencyFactory.Create(this);
    }
}

var kernel = new StandardKernel();
kernel.Bind<Controller>().To<MyController>();
kernel.Bind<IDependency>().To<DependencyImplementation>();
kernel.Bind<IDependencyFactory>().ToFactory();
var controller = kernel.Get<Controller>();

Or maybe rather reconsider whole design.

Jan Muncinsky
  • 4,282
  • 4
  • 22
  • 40