Solving a cyclical dependency in Ninject (Compact Framework)
- by Alex
I'm trying to use Ninject for dependency injection in my MVP application. However, I have a problem because I have two types that depend on each other, thus creating a cyclic dependency. At first, I understand that it was a problem, because I had both types require each other in their constructors. Therefore, I moved one of the dependencies to a property injection instead, but I'm still getting the error message. What am I doing wrong?
This is the presenter:
public class LoginPresenter : Presenter<ILoginView>, ILoginPresenter
{
public LoginPresenter( ILoginView view )
: base( view )
{
}
}
and this is the view:
public partial class LoginForm : Form, ILoginView
{
[Inject]
public ILoginPresenter Presenter { private get; set; }
public LoginForm()
{
InitializeComponent();
}
}
And here's the code that causes the exception:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[MTAThread]
static void Main()
{
// Show the login form
Views.LoginForm loginForm = Kernel.Get<Views.Interfaces.ILoginView>() as Views.LoginForm;
Application.Run( loginForm );
}
}
The exception happens on the line with the Kernel.Get<>() call. Here it is:
Error activating ILoginPresenter using binding from ILoginPresenter to LoginPresenter
A cyclical dependency was detected between the constructors of two services.
Activation path:
4) Injection of dependency ILoginPresenter into property Presenter of type LoginForm
3) Injection of dependency ILoginView into parameter view of constructor of type LoginPresenter
2) Injection of dependency ILoginPresenter into property Presenter of type LoginForm
1) Request for ILoginView
Suggestions:
1) Ensure that you have not declared a dependency for ILoginPresenter on any implementations of the service.
2) Consider combining the services into a single one to remove the cycle.
3) Use property injection instead of constructor injection, and implement IInitializable
if you need initialization logic to be run after property values have been injected.
Why doesn't Ninject understand that since one is constructor injection and the other is property injection, this can work just fine? I even read somewhere looking for the solution to this problem that Ninject supposedly gets this right as long as the cyclic dependency isn't both in the constructors. Apparently not, though. Any help resolving this would be much appreciated.