views:

202

answers:

2
+1  Q: 

Unity and delegate

Hi

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?

A: 

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.

Joe
+2  A: 

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);
            }
        }
    }
Steven Robbins