Search code examples
c#dependency-injectioncircular-dependencyanemic-domain-model

Circular reference between the services using the Anemic domain model


I am working on a project with a complex business. Consider two classes : AccountService and SchoolService

I am using Unity and the dependency resolver of the Web API to implement dependency injection in the constructor.

The school service uses the account service in some methods, also the account service uses the school service. All this is required in the business of the project. This will cause circular dependency, and it is not possible to move the methods from one class into another.

Can you please provide any idea on how to solve this ?

Here is an example:

public class SchoolBLC : ISchoolBLC
{
    public School GetSchool(int schoolId)
    {
        ...
    }

    public bool RenewRegistration(int accountId)
    {
        bool result = true;

        IAccountBLC accountBLC = new AccountBLC();
        // check some properties related to the account to decide if the account can be renewed
        // ex : the account should not be 5 years old
        // check the account created date and do renewal

        return result;
    }
}

public class AccountBLC : IAccountBLC
{
    public void ResetAccount(int accountId)
    {
        ISchoolBLC schoolBLC = new SchoolBLC();
        School accountSchool = schoolBLC

        // get the school related to the account to send a notification 
        // and tell the school that the user has reset his account
        // reset account and call the school notification service
    }

    public Account GetAccount(int accountId)
    {
        ...
    }
}

The two classes are referencing each other, this is the situation for 70% of the BLCs in the project.


Solution

  • If you absolutely have to do it that way you can have an interface that does your IoC logic and resolve that to an implementation that wraps Unity's resolution, e.g.

    public interface ITypeResolver
    {
        T Resolve<T>();
    }
    

    Then you can pass that interface to both services in the constructor and use it to lazy-resolve the other service before you use it, outside the constructor.

    That way when both services are initialized they will not have a direct dependency on the other service, only on ITypeResolver