What is Inversion of Control?

前端 未结 30 2839
清歌不尽
清歌不尽 2020-11-22 00:13

Inversion of Control (IoC) can be quite confusing when it is first encountered.

  1. What is it?
  2. Which problem does it solve?
  3. When is it appropria
30条回答
  •  醉酒成梦
    2020-11-22 00:40

    1. So number 1 above. What is Inversion of Control?

    2. Maintenance is the number one thing it solves for me. It guarantees I am using interfaces so that two classes are not intimate with each other.

    In using a container like Castle Windsor, it solves maintenance issues even better. Being able to swap out a component that goes to a database for one that uses file based persistence without changing a line of code is awesome (configuration change, you're done).

    And once you get into generics, it gets even better. Imagine having a message publisher that receives records and publishes messages. It doesn't care what it publishes, but it needs a mapper to take something from a record to a message.

    public class MessagePublisher
    {
        public MessagePublisher(IMapper mapper,IRemoteEndpoint endPointToSendTo)
        {
          //setup
        }
    }
    

    I wrote it once, but now I can inject many types into this set of code if I publish different types of messages. I can also write mappers that take a record of the same type and map them to different messages. Using DI with Generics has given me the ability to write very little code to accomplish many tasks.

    Oh yeah, there are testability concerns, but they are secondary to the benefits of IoC/DI.

    I am definitely loving IoC/DI.

    3 . It becomes more appropriate the minute you have a medium sized project of somewhat more complexity. I would say it becomes appropriate the minute you start feeling pain.

提交回复
热议问题