0

我正在寻找一个 FAST IoC 容器并找到了 Dynamo.IoC。

让它像一个简单的 ServiceLocator 一样工作很容易,但是如何将它用于构造函数注入呢?

这是示例类

    private interface ITestInterface
    {

    }

    private class TestClass : ITestInterface
    {

    }

    private class TestClassWithDependency
    {
        public ITestInterface DependecyInstance { get; private set; }

        public TestClassWithDependency( ITestInterface dependencyInstance )
        {
            DependecyInstance = dependencyInstance;
        }
    }

和失败的测试

    [Test]
    public void Test_Container_Resolve_WithDependency()
    {
        Container.Register<ITestInterface, TestClass>();

        var obj = Container.Resolve<TestClassWithDependency>( );


        obj.Should().NotBeNull();
        obj.DependecyInstance.Should( ).NotBeNull( );
    }
4

1 回答 1

0

我认为您需要使用带有接口的参数化构造函数注册类。然后像往常一样注册它。RegisterType,你可以注入“dependencyInstance”。请看下文。

public interface ITestInterface
{}

public class TestClass : ITestInterface
{}

public interface ITestClassWithDependency {
    ITestInterface DependecyInstance { get;  }
}

public class TestClassWithDependency : ITestClassWithDependency
{
    public ITestInterface DependecyInstance { get; private set; }


    public TestClassWithDependency(ITestInterface dependencyInstance)
    {
        DependecyInstance = dependencyInstance;
    }
}

public class MyClass
{
    [Test]
    public void Test_Container_Resolve_WithDependency()
    {
        using (var container = new IocContainer())
        {
            container.Register<ITestInterface, TestClass>();
            container.Register<ITestClassWithDependency, TestClassWithDependency>();

            var obj = container.Resolve<ITestClassWithDependency>();

            Assert.IsNotNull(obj);
            Assert.IsNotNull(obj.DependecyInstance);
        }

    }
}
于 2013-10-08T12:46:38.760 回答