【问题标题】:How to solve Cyclic Dependency如何解决循环依赖
【发布时间】:2016-09-21 16:45:38
【问题描述】:
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;

    }

}

我遇到了两个类相互依赖的情况。我正在使用忍者。

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

上面的代码导致循环依赖。 解决这个问题的正确方法是什么?请分享一些代码。

【问题讨论】:

  • 问一个简单的问题:在没有任何 DI 容器的情况下如何使用这些类?
  • @MaKCbIMKo 提出了一个非常应该尝试回答的重要问题。
  • @MaKCbIMKo 我正在使用 Ninject IoC 容器
  • 我的意思是,如果你有一个循环依赖,这意味着你的软件设计有问题。

标签: c# dependency-injection ninject service-layer


【解决方案1】:

循环依赖表示您的软件中存在设计或建模问题。虽然你可以使用属性注入来构造你的对象图,但是你会忽略根本原因并添加另一个问题:属性注入导致Temporal Coupling。

相反,解决方案是仔细查看设计。通常你会发现有第三种“隐藏”的服务需要被抽象出来。两种服务都可以依赖这项新服务。

由于您的问题非常高级,仅涉及接口名称和组件之间的依赖关系,因此很难具体说明,但这里有一个可能的解决方案:

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

【讨论】:

  • 在我的例子中,Logger 类也将依赖于 NotificationService 和 LogService,这将创建另一个循环依赖。
【解决方案2】:

对一个(或两个)类使用属性注入: 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;
    }
}

【讨论】:

    猜你喜欢
    • 2012-03-15
    • 2020-11-12
    • 2021-04-26
    • 2011-08-16
    相关资源
    最近更新 更多