Unity and delegate

情到浓时终转凉″ 提交于 2019-12-10 17:46:09

问题


I'm using the Unity dependency injection framework. I have two classes, that each take the same delegate parameter in the constructor. Each class should get a different method when resolved. Can I set this up without using attributes ? If not how would you do it with attributes?


回答1:


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

This example isn't using delegates, it's just using an interface instead, but it shows two of the same interface being registered with different names, and a class requesting a particular 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);
            }
        }
    }



回答2:


Instead, you could try passing a factory in on the constructor of the objects. That way you can guarantee (and test) in code exactly what objects are created.



来源:https://stackoverflow.com/questions/1508359/unity-and-delegate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!