.NET Core Web API dependency injection (DI) conducted a service configuration

 

  Design framework ASP.NET Core from start to finish are modular, and follow good software engineering practices. In object-oriented programming, SOLID withstood the test of time. ASP.NET Core has the dependency injection into the core framework. Regardless of whether you want to use dependency injection into your own code, ASP.NET Core dependency injection framework has been put as a basic concept.

  SOLID is Single responsibility, Open-closed, Liskov substitution, Interface segregation, Dependeny inversion shorthand: https://zh.wikipedia.org/zh-hans/SOLID_ (object oriented design)

        Dependency Injection introduction reference links: https://www.martinfowler.com/articles/injection.html

1. understand the benefits of dependency injection

  In a simple application, we use less than dependency injection, but when the application becomes too complex when dependency injection (DI) can be used as a great tool to control the complexity of the code.

  Let's look at an example, when not in use DI, after a user registration on your Web applications, you want to give it to send a message, the following code shows that you can deal with this problem in the first time.

  In this example, when a new user registered your Web application, in UserControllor RegeditUser

It will be performed. EmailSender first create an instance of a class, and call SendEmail () methods to send messages. In this case, you can imagine will see the following contents:

Console.WriteLine will perform an email.

  If EmailSender simple class like in this case and no dependencies, you might not consider using other methods to create objects. In a way, you may have when right. But if you update EmailSender implementation logic later, we find all logic it does not implement its own outgoing mail.

      In fact, EmailSender when sending messages need to do a lot of things:

      1. Create an email message

    2. configuration settings email services

      3. emial server to send mail

  If you implement the above functions in a class, it would violate the principle of duty units (SRP), so you can not let EmialSender depend on other services. The following figure shows will depend on Web applications will look like. UserController want to send the message using EmailSender, but if you do so, you first need to create a MessageFactory, NetworkClient, EmailServerSettings object to the EmailSender provide dependent.

  Each class requires a lot of dependence, in this case as a class UserController "bottom", you need to know how to create it depends on each class, and the dependencies of each class.

Examples of multiple dependent services are as follows:

Examples NetworkClient dependent code is as follows:

  In this way you may feel a lot of trouble, but this dependency chain is very common. In fact, your code does not write, your class will be very large, and contrary to the principle of single responsibility. When you manually create a dependency, when sending mail is not the DI. Code as follows:

  The code example above into a code number rough. When you call in UserController, in order to improve the design of EmailSender to separate out the different responsibilities, it became a hassle. The code has the following problems.

         1. did not follow the single responsibility principle - our code at the same time responsible for creating EmailSender instance and use it to send e-mail.

          2. sizeable method code - RegeditUser the above method, only the last two lines of code to be useful. What is difficult to understand the real purpose of this method is yes.

        3. Binding and realize - if you decide to reconstitute EmialSender and to add another dependent, you need to update it every place of use.

  UserController has clearly dependent on the EmailSender class, and manually create an instance of this object as a method RegeditUser department. In reading the source code only know UserController used EmailSender. In contrast, EmialSender has clearly dependent on the NetworkClient and MessageFactory, and is initialized in the constructor. The same, NetworkClient has clearly depends on the EmailServerSetting class.

  Dependency injection is intended to pull off the reverse dependency chain. Instead UserController to manually create a dependency, further details of the implementation code has been created by the injection to create instances EmailSender constructor.

  Now, obviously, and some things need to create objects, these objects need to survive in the code somewhere. Responsible for creating an object or container service called DI IoC container. Common DI container has: Autofac, StructureMap, Unity, Ninject, Simple Injector... 

  FIG DI container using the following relationship:

  At this time, the UserController code as shown below:

 

  Advantages DI container of said single responsibility: to create an object or service. A service request to the instance of the container, and calculates the oxygen creates a dependency graph, but they are dependent on how to configure them.

  Use obvious advantage is dependent, in a way you would never write a chaotic way. DI container can check your constructor and services and to calculate an important part of the code itself. DI container is configurable, so you can create an instance of the service can be provided manually. It can interface to make your code remains loosely coupled.

  In object-oriented languages ​​coupling is a very important concept. It noted that a class how to rely on other classes and performs its own function. Loosely coupled code does not need to know a lot of details of a particular component, you can directly go to use it.

  In UserController initialized EmailSender said tightly coupled, you need to create an instance of EmialSender direct. One difficulty is that the code is difficult to test, any attempt UserController test methods will lead to send the message. The EmailSender as a constructor argument, create and delete objects duties will reduce coupling of the code. If implemented EmialSender changed, it relies on another implementation, the update does not need to update at the same time UserController.

      Through the interface into the design pattern is a common method, which reduces the coupling system. And it will not be bound to a single implementation, and it also allows the class change can be tested. So you can create a IEmialSender interface that allows EmailSender achieve it:

User control codes are as follows:

 

  Now UserController has no dependent care is how to achieve, and only realized IEmailSender interfaces and exposed SendEmail method. Now the application code independent of the already achieved. Now we have achieved a loosely coupled code. But there is another problem: the application knows how to use EmailSender to replace DummyEmailSender, DI container to tell you the answer: when you need IEmailSender, use EmailSender to register.

  How to register interface and implementation are very dependent DI container implementations in DI container, but the basic principles are the same for all the DI container. ASP.NET Core contains a simple DI container out of the box, so let's see how to use it in a typical request.

2. In use dependency injection ASP.NET Core

  This chapter details the content will be explained in detail in the next blog.

      

     

 

Guess you like

Origin www.cnblogs.com/fengye310/p/11008950.html