依赖注入问题(双向通信) [英] Dependency injection issue (bidirectional communication)

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

问题描述

我有 a A b B

a 的实例必须能够要在 b b 上调用方法,则必须立即在 a上调用方法如果某些检查通过。

a must be able to call a method on b and b must then immediatly call a method on a if some checks pass.

要实现这一点,我将使用循环DI

To achieve this I would have cyclic DI

public A(B b) { _b = b; }
public void CallToB() { _b.Method(); }
public void Method() { DoSomething(); }

public B(A a) { _a = a; }
public void Method() { if (SomeCheck()) _a.Method(); }

我知道我可以通过使用事件让 b 不知道/独立于 a

I know I could get arround this, using events and let b be unaware/independant of a. But it would feel wrong.

注意:在实现双向通讯的情况下,我没有看到这个问题的答案。

Note: I haven't seen an answer to this question where bidirectional communication was made possible.

推荐答案

您可以通过依赖接口而不是具体类型来解决此问题,然后使用属性注入。下面是一个示例:

You can solve this issue by depending on interfaces instead of concrete types and then use property injection. Here is an example:

public interface IA
{
    void Method();
}

public class A : IA
{
    private readonly IB _b;
    public A(IB b){_b = b;}
    //...
}

public interface IB
{
    void Method();
}

public class B : IB
{
    private readonly IA _a;
    public B(IA a){_a = a;}
    //...
}

public class BCycleDependencyBreaker : IB
{
    private IB _b;

    public IB b
    {
        set { _b = value; }
    }

    public void Method()
    {
        _b.Method();
    }
}

然后使用 BCycleDependencyBreaker ,例如:

var b_cycle_dependency_breaker = new BCycleDependencyBreaker();

//Make a depend on this implementation of b that currently does nothing
A a = new A(b_cycle_dependency_breaker); 

//Make b depend on a
B b = new B(a);

//Now, let the proxy implementation delegate calls to the real b
b_cycle_dependency_breaker.b = b;

这篇关于依赖注入问题(双向通信)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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