How to solve Cyclic Dependency

2019-09-02 18:27发布

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.

2条回答
在下西门庆
2楼-- · 2019-09-02 18:30

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;
    }
}
查看更多
forever°为你锁心
3楼-- · 2019-09-02 18:47

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;
    }
}
查看更多
登录 后发表回答