Unity and delegate

I use the Unity dependency injection infrastructure. I have two classes, each of which takes the same delegate parameter in the constructor. When resolving, each class should receive a different method. Can I customize this without using attributes? If not, how would you do with attributes?

+3
source share
2 answers

Yes, you can decorate constructor properties or parameters with the [Dependency] attribute.

In this example, delegates are not used, but just an interface is used, but it shows two identical interfaces registered with different names, and a class requesting a specific one in its constructor:

    [TestClass]
    public class NamedCI
    {
        internal interface ITestInterface
        {
            int GetValue();
        }

        internal class TestClassOne : ITestInterface
        {
            public int GetValue()
            {
                return 1;
            }
        }

        internal class TestClassTwo : ITestInterface
        {
            public int GetValue()
            {
                return 2;
            }
        }

        internal class ClassToResolve
        {
            public int Value { get; private set; }

            public ClassToResolve([Dependency("ClassTwo")]ITestInterface testClass)
            {
                Value = testClass.GetValue();
            }
        }

        [TestMethod]
        public void Resolve_NamedCtorDependencyRegisteredLast_InjectsCorrectInstance()
        {
            using (IUnityContainer container = new UnityContainer())
            {
                container.RegisterType<ITestInterface, TestClassOne>("ClassOne");
                container.RegisterType<ITestInterface, TestClassTwo>("ClassTwo");
                container.RegisterType<ClassToResolve>();

                var resolvedClass = container.Resolve<ClassToResolve>();

                Assert.AreEqual<int>(2, resolvedClass.Value);
            }
        }

        [TestMethod]
        public void Resolve_NamedCtorDependencyRegisteredFirst_InjectsCorrectInstance()
        {
            using (IUnityContainer container = new UnityContainer())
            {
                container.RegisterType<ITestInterface, TestClassTwo>("ClassTwo");
                container.RegisterType<ITestInterface, TestClassOne>("ClassOne");
                container.RegisterType<ClassToResolve>();

                var resolvedClass = container.Resolve<ClassToResolve>();

                Assert.AreEqual<int>(2, resolvedClass.Value);
            }
        }
    }
+3
source

Instead, you can try passing the factory to the object constructor. Thus, you can guarantee (and check) in the code exactly which objects are created.

0
source

Source: https://habr.com/ru/post/1719073/


All Articles