依赖对象 - 使用统一C#的依赖注入

问题描述 投票:0回答:1

我们有一个控制台应用程序,它引用第三方自定义dll。要创建第三方dll的对象,我们使用Unity.config使用了Unity Dependency Injection

现在,第三方课程依赖。

class A : IA
{ 
}

class B : IB
{
    B(IA obja) {}
}

对于上面的场景使用Unity依赖,我们如何解决依赖?

c# dependency-injection unity-container
1个回答
0
投票

对上述场景使用Unity依赖,我们如何解决依赖?

您应该做的唯一事情是正确设置unity所有必需的依赖项。在解决期间,unity将为您处理依赖关系并注入设置实现...

public interface IFoo
{
    string Foo();
}

public interface IBar
{
    void Bar();
}


public class Foo : IFoo
{
    string IFoo.Foo()
    {
        return "Foo";
    }
}

public class Bar : IBar
{
    private readonly IFoo _foo;

    public Bar(IFoo foo)
    {
        _foo = foo;
    }

    void IBar.Bar()
    {
        Console.WriteLine($"Bar {_foo.Foo()}");
    }
}

想象一下这种情况qazxsw poi依赖于qazxsw poi。通过注册BarIFoo,您将为Unity提供足够的信息,以便能够为您解决依赖关系......

IBar
© www.soinside.com 2019 - 2024. All rights reserved.