A
A
Alexveto2021-02-25 21:54:23
ASP.NET
Alexveto, 2021-02-25 21:54:23

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;
   }
}

2) PersonDataProvider
public class PersonaDataProvider : IPersonaDataProvider
{
   private IAccountsService AccountsService { get; }

   public PersonaDataProvider(IAccountsService accountsService)
   {
      AccountsService = accountsService;
   }
}

3) Well, AccountsService:
public class AccountsService : IAccountsService
{
   private IPersonaDataProvider PersonaDataProvider { get; }

   public AccountsService(IPersonaDataProvider personaDataProvider)
   {
      PersonaDataProvider = personaDataProvider;
   }

Throws an error: System.MissingMethodException: There are no parameterless constructors defined for this object.

As I understand it, when creating a HomeController object, it tries to create an IPersonaDataProvider object, but to create it, it needs an IAccountsService object, and to create an IAccountService object, it needs an IPersonaDataProvider object, it turns out a vicious circle.

How to resolve such a situation?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MrDywar Pichugin, 2021-02-25
@Alexveto

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 question

Ask a Question

731 491 924 answers to any question