Reputation: 7328
I am using Ninject, and using Constructor Injection:
An example of my problem is
I have two interfaces with their implementations.
1. IUsersProvider
2. ICompaniesProvider
I need to use functions from UsersProvider
in CompaniesProvider
And from CompaniesProvider
in UsersProvider
So I have created Constructors in both classes:
public class UsersProvider : IUsersProvider
{
private readonly ICompaniesProvider _companiesProvider;
public UsersProvider(ICompaniesProvider companiesProvider)
{
_companiesProvider = companiesProvider;
}
}
AND
public class CompaniesProvider : ICompaniesProvider
{
private readonly IUsersProvider _usersProvider;
public UsersProvider(IUsersProvider usersProvider)
{
_usersProvider = usersProvider;
}
}
Now this code compiles ok but from an architecture point of view this not correct (It looks like a circular reference). Ninject throws an exception when I run this code:
what is the best way of handling the scenario to use functions from each class in the other?
Upvotes: 1
Views: 61
Reputation: 5427
The correct way to handle this scenario would be to refactor one or both interfaces/classes so that they don't depend on each other. It's hard to advise with more detail without seeing the code of each, but typically if you find yourself in this situation, one or both of your classes are doing too much, i.e., violating Single Responsibility Principle. split up the interface so it only does one thing, and then your dependencies should clear up.
Upvotes: 4