0
public class NotificationService: INotificationService{

    private ILogService _logService;

    public NotificationService(ILogService logService){

        _logService = logService;

    }

}


public class LogService: ILogService{

    private INotificationService _notificationService;

    public LogService(INotificationService notificationService){

    _notificationService = notificationService;

    }

}

I came into a situation where two classes depends on each other. I am using Ninject.

Bind<INotificationService>().To<NotificationService>();
Bind<ILogService>().To<LogService>();

The codes above are causing Cyclic Dependency. What is the proper way to solve this? Please share some codes.

h3n
  • 5,142
  • 9
  • 46
  • 76

2 Answers2

3

A cyclic dependency is an indication of a design or modeling problem in your software. Although you can construct your object graph by using property injection, you will ignore the root cause and add another problem: property injection causes Temporal Coupling.

Instead, the solution is to look at the design closely. Often you will find that there is a third 'hidden' service that needs to be abstracted. Both services can depend on this new service.

Since your question is quite high-level with just the interface names and the dependencies between the components, it's hard to be specific, but here's an possible solution:

public class Logger : ILogger { }

public class NotificationService : INotificationService{
    private ILogger _logger;

    public NotificationService(ILogger logger){
        _logger = logger;
    }
}

public class LogService : ILogService {
    private ILogger _logger;

    public LogService(ILogger logger){
        _logger = logger;
    }
}
Steven
  • 166,672
  • 24
  • 332
  • 435
  • In my case, the Logger class will also depends on NotificationService and LogService which will create another cyclic dependency. – h3n May 25 '16 at 09:40
1

Use property injection for one (or both) of the classes: Cyclic dependency with ninject

public class NotificationService: INotificationService{

    ILogService LogService { set; }
}


public class LogService: ILogService{

    private INotificationService _notificationService;

    public LogService(INotificationService notificationService){
    {
        notificationService.LogService = this;
    }
}
Community
  • 1
  • 1
Ryan Peters
  • 180
  • 9