Answer the question
In order to leave comments, you need to log in
How to correctly set up Dependency Injection in ASP.NET MVC?
Initial data:
0) ASP.NET MVC 5
1) There is a Home controller into which the dependency is injected using Ninject
public class HomeController : Controller
{
private IPersonaDataProvider PersonaDataProvider { get; }
public HomeController(IPersonaDataProvider personaDataProvider)
{
PersonaDataProvider = personaDataProvider;
}
}
public class PersonaDataProvider : IPersonaDataProvider
{
private IAccountsService AccountsService { get; }
public PersonaDataProvider(IAccountsService accountsService)
{
AccountsService = accountsService;
}
}
public class AccountsService : IAccountsService
{
private IPersonaDataProvider PersonaDataProvider { get; }
public AccountsService(IPersonaDataProvider personaDataProvider)
{
PersonaDataProvider = personaDataProvider;
}
Answer the question
In order to leave comments, you need to log in
You need to unlock the dependencies.
When Dependency Injection tries to resolve the "deepest" dependency, in your case IAccountsService, it can't do it because encounters a cycle.
You need to change the relationships between classes, for example, add a new service that receives IAccountsService and IPersonDataProvider, while IAccountsService and IPersonaDataProvider themselves should not depend on each other, i.e. become independent of each other.
This is if you want to use constructor injection, as in the examples above.
Another solution, I don't really think for your situation, is to use property injection. It will work even with a cyclic dependency.
There is a good book on this topic - Siman Mark "Dependency Injection in .NET".
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question