如何使用统一注入依赖(基础)?

时间:2017-02-14 10:06:52

标签: c# unity-container

我是依赖注入的初学者。我在控制台应用程序中使用Microsoft Unity开始并刷新基础知识。我想根据类I注册到接口引用来调用Addition Class或Substraction Class的方法。但我得到引用InterfaceReference为null。请在下面的案例中建议我做错了什么?

我使用了一个界面 -

namespace ConsoleApplication3
{
    interface IArithmetic
    {
        int DoOperation(int a, int b);
    }
}

和2个claess -

namespace ConsoleApplication3
{
    class Addition : IArithmetic
    {
        public int DoOperation(int a, int b)
        {
            return a + b;
        }
    }
}

namespace ConsoleApplication3
{
    class Substraction : IArithmetic
    {
        public int DoOperation(int a, int b)
        {
            return a - b;
        }
    }
}



namespace ConsoleApplication3
{
    class Program
    {
        private static IArithmetic InterfaceReference;

        public Program(IArithmetic InterfaceReferenceParam)
        {
            InterfaceReference = InterfaceReferenceParam;
        }

        static void Main(string[] args)
        {

            IUnityContainer myContainer = new UnityContainer();
            myContainer.RegisterType<IArithmetic, Addition>();
            int output = InterfaceReference.DoOperation(5, 2);
            Console.Write(output);
            Console.WriteLine();
        }
    }
}

2 个答案:

答案 0 :(得分:1)

您没有实例化您的Program类,因此注入IArithmetic实现的构造函数永远不会运行。您需要使用Unity Resolve来创建Program类的实例。看看Using Unity DI with a Console Application

类似下面的代码(我暂时没有使用unity,所以我不确定语法是否完全正确)。基本上您还需要使用Unity注册Program类,然后使用Unity Resolve方法创建Program的实例。因为Unity了解Program,所以这个解决方案将为Program创建依赖树。

namespace ConsoleApplication3
{
    class Program
    {
        private IArithmetic InterfaceReference;

        public Program(IArithmetic InterfaceReferenceParam)
        {
            InterfaceReference = InterfaceReferenceParam;
        }

        public void Run()
        {
            int output = InterfaceReference.DoOperation(5, 2);
            Console.Write(output);
            Console.WriteLine();

        }

        static void Main(string[] args)
        {
            IUnityContainer myContainer = new UnityContainer();
            myContainer.RegisterType<IArithmetic, Addition>();
            myContainer.RegisterType<Program, Program>();
            var program = myContainer.Resolve<Program>();
            program.Run();
        }
    }
}

答案 1 :(得分:0)

问题是您在注册类型后没有调用Unity Resolve方法。例如,这将起作用:

class Program
{
    static void Main(string[] args)
    {
        IUnityContainer container = new UnityContainer();
        container.RegisterType(typeof(IArithmetic), typeof(Addition));
        var arithmeticHelper = container.Resolve<IArithmetic>();
        int output = arithmeticHelper.DoOperation(5, 2);
        Console.Write(output);
        Console.ReadKey();
    }
}