Can someone explain Microsoft Unity?

前端 未结 7 1664
被撕碎了的回忆
被撕碎了的回忆 2020-12-07 06:55

I\'ve been reading the articles on MSDN about Unity (Dependency Injection, Inversion of Control), but I think I need it explained in simple terms (or simple examples). I\'m

7条回答
  •  甜味超标
    2020-12-07 07:29

    Unity is a library like many others that allows you to get an instance of a requested type without having to create it yourself. So given.

    public interface ICalculator
    {
        void Add(int a, int b);
    }
    
    public class Calculator : ICalculator
    {
        public void Add(int a, int b)
        {
            return a + b;
        }
    }
    

    You would use a library like Unity to register Calculator to be returned when the type ICalculator is requested aka IoC (Inversion of Control) (this example is theoretical, not technically correct).

    IoCLlibrary.Register.Return();
    

    So now when you want an instance of an ICalculator you just...

    Calculator calc = IoCLibrary.Resolve();
    

    IoC libraries can usually be configured to either hold a singleton or create a new instance every time you resolve a type.

    Now let's say you have a class that relies on an ICalculator to be present you could have..

    public class BankingSystem
    {
        public BankingSystem(ICalculator calc)
        {
            _calc = calc;
        }
    
        private ICalculator _calc;
    }
    

    And you can setup the library to inject a object into the constructor when it's created.

    So DI or Dependency Injection means to inject any object another might require.

提交回复
热议问题