如何解决循环依赖 [英] How to solve Cyclic Dependency

查看:129
本文介绍了如何解决循环依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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;

    }

}

我遇到了两个阶级相互依赖的情况.我正在使用Ninject.

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.

推荐答案

循环依赖项表示软件中存在设计或建模问题.尽管您可以使用属性注入来构造对象图,但是您将忽略根本原因并添加另一个问题:属性注入导致时间耦合.

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

这篇关于如何解决循环依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆