依赖注入与循环依赖 [英] Dependency Injection with Cyclic Dependency

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

问题描述

让我有两个非常基本的对象,例如:

Let me have two very basic objects like:

public class View
{
    public View(Controller controller)
    {
        // Use the model exposed by the controller here
    }
}

public class Controller
{
    private readonly IView view;

    public Controller()
    {
        this.view = new View(this);
    }

    public Controller(View v)
    {
        this.view = v;
    }
}

后来我决定通过以下方式将View对象注入Controller DI,但我有一个周期性的依赖关系(即我不能使用 var ctrl = new Controller(new View(ctrl)); )。在这种情况下,如何注入依赖项?

Later I decide to inject View object into the Controller via DI but there I have a cyclic dependency (i.e. I can't use var ctrl = new Controller(new View(ctrl));). How would you go about injectin the dependency in this case?

推荐答案

最常见的解决方案是使用依赖项属性来解决循环问题依赖性。即在其中一个类中创建一个新属性,并让IoC容器为其分配。

The most common solution is to use a dependency property to solve circular dependencies. i.e. create a new property in one of the classes and let the IoC container assign it.

如果您使用Unity,则应添加 [Dependency] 到该属性。

If you are using Unity you should add [Dependency] to that property.

边注:View不应依赖于控制器。

A sidenote: A View should not have a dependency to a controller. It should not be aware of it at all.

更新以回复评论

你不能。这就是循环依赖的问题。唯一的其他解决方案是使用合成。那就是将通用功能分解为一个单独的类,并将其包含在控制器和视图中。

You can't. That's the problem with circular dependencies. The only other solution is to use composition. That is to break out the common functionality into a separate class and include it in both the controller and the view.

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

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