[ASP.NET Core 3 frame Disclosure] dependency injection: Inversion of Control

ASP.NET Core framework built on the basis of some core framework, the basic framework, including dependency injection, file systems, configuration options and diagnostic logs. These frameworks are not just supporting basic ASP.NET Core framework, making application development time we will also frequently used to them. For these few basic framework mentioned here, dependency injection is particularly important. ASP.NET Core Application startup and subsequent request for processing, it will rely on a variety of service components. To facilitate customization, these components will generally be "normalized" in the form of interface, we will standardize these components collectively referred to as "Service (Service)". ASP.NET Core entire frame based on a frame underlying dependency injection, which uses dependency injection container to provide the desired service object. To understand this dependency injection container and its service delivery mechanisms, we must first know what a "dependency injection (DI: Dependence Injection)". Once we mentioned dependency injection, they had to talk about the "Inversion of Control (IoC: Inverse of Control)".

A flow inversion control

Some so-called design software development often without a clear definition, such as the popular SOA before and now so hot "micro-services (Micro Service)" and "no server (Serverless)", we did not pass a law clear "meaning" to give them a precise definition, but only from the description of the "extension" should have these kind of architecture design characteristics. Because we not give a clear definition, which caused a lot of people have different interpretations often for the same concept. IoC is also the case for so represent only one of the words the author of this chapter, readers tentatively listen to it, for reference only.

I have heard many people will IoC said to be a kind of "object-oriented design patterns", but in my personal opinion IoC not only can not be regarded as a kind of "design mode", which itself has no direct relationship with the "object-oriented" . Reason why many people can not understand IoC very accurate, due to their neglect one of the most fundamental things that IoC phrase itself.

IoC full name Inverse of Control, translated into Chinese is " inversion of control " or " control upside down ." Inversion of Control or, inversion of control worth mentioning, it reflects the mean transfer of control of that control in the hands of the original A, B and now need to take over. So for software designs, IoC so-called transfer of control has what it embodied? To answer this question, we need to understand IoC of C (Control) actually refers to what kind of control. For any task where we are, irrespective of their size, can be substantially decomposed to the corresponding step, any one embodiment so the task has its inherent processes, and relates to the control IoC can be understood as " control process for . "

Through a specific example to illustrate the traditional design for the flow of control is how to achieve reversal after using IoC. For example, we want to design a library for the Web MVC, it might be named MvcLib. For simplicity, this library contains only static class follows the same name.

public static class MvcLib
{
    public static Task ListenAsync(Uri address);
    public static Task<Request> ReceiveAsync();
    public static Task<Controller> CreateControllerAsync(Request request);
    public static Task<View> ExecuteControllerAsync(Controller controller);
    public static Task RenderViewAsync(View view);
}

MvcLib provided above five ways to help us complete the entire HTTP request process in five core tasks. Specifically, ListenAsync method starts a listener and bind it to the designated address listening HTTP request, the request arriving via ReceiveAsync receiving method for receiving a request to be represented by a Request object. CreateControllerAsync analytical method and activating a target Controller object according to the received request. ExecuteControllerAsync method of performing activation and returns Controller View object represents a view. RenderViewAsync ultimately View objects into HTML content as the current request and returns the response to the requesting client.

Now we create a true MVC application on the basis of this MvcLib. In addition we find that according to custom specifications MvcLib specific and View Controller, we also need to self-control the entire process from the final presentation monitor the received request, performing activation and Controller View, and including, the implementation of such a flow It is reflected in the code shown below.

class Program
{
    static async Task Main()
    {
        while (true)
        {
            var address = new Uri("http://0.0.0.0:8080/mvcapp");
            await MvcLib.ListenAsync(address);
            while (true)
            {
                var request = await MvcLib.ReceiveAsync();
                var controller = await MvcLib.CreateControllerAsync(request);
                var view = await MvcLib.ExecuteControllerAsync(controller);
                await MvcLib.RenderViewAsync(view);
            }
        }
    }
}

This example reflects the flow control mode as shown below (application code completely asynchronous way to deal with the request, in order to allow a flow chart of even more simple, we are drawn into the form of a flow chart of the synchronization, the reader does not have to tangle this problem ). We designed the library (MvcLib) provides only achieve a variety of functions in the form of a single API, a library consumer application (App) you will need to arrange their own entire workflow. If the code reuse perspective, here are limited to reuse code to achieve a particular aspect of a single function, choreography entire workflow code is not reused .

3-1

But in the real development scenario, we need more than just a class library provides a single API, but can build applications directly on top of the frame. Library (Library) and framework (Framework) the difference is that: the former is often only provide a single API to implement some functions, while the latter against a target task scheduling form a complete process for these single function, and the use of a engine driving this process automatically.

For our MvcLib demonstrated above, the application needs as consumers of their own process for controlling the entire HTTP request, but in fact this is a very " generalization " of the workflow, almost all of the MVC applications are used in such a process to monitor, receive requests and eventual response to the request. If we implement this process in a MVC framework, all of it built by the MVC application can be used directly request processing flow, do not need to make unnecessary DIY (Do It Yourself).

Now we will transform MvcLib from the library into a framework, tentatively referred to as MvcFrame. Shown below, MvcFrame core is referred to as a MvcEngine execution engine, which drives a choreographed workflow consistent processing HTTP requests. If we use MvcFrame build a specific application of MVC, except in accordance with our business requirements definition than the corresponding Controller and View, we only need to initialize the engine and it can be started directly. If you've ever worked on ASP.NET MVC application, you will find that ASP.NET MVC is such a framework.

3-2

With the presentation of this front as an example of foreshadowing, we should be very easy to understand IoC say on the so-called inversion of control is essentially what it is. Overall, IoC is a basic idea of the design framework we adopted the so-called inversion of control is the application of process control is transferred to the frame . Take the previous example, in the era of the traditional library-oriented programming, an HTTP request processing flow control firmly in the hands of the application. After the introduction of the frame, the transfer request processing control to the hands of the frame.

Second, Hollywood rule

In Hollywood, actors resume only after the company submitted to the performing arts go home and wait. Since the performing arts company has full control over the entire entertainment, movie actor can only passively accept the company's offer. "Do not call us, we'll call you (Do not call us, we'll call you)" This is the law of the famous Hollywood (Hollywood Principle or Hollywood Low), IoC perfectly embodies this principle.

3-3

In the context of IoC, the frame is like a master filmmaker whole process of film companies, because it is the de facto control of the entire workflow, so it only needs to know which staff which links. Applications like actor, it only needs to register these components in accordance with the rules can be customized framework, because the framework will automatically load and execute the components registered at the right time.

To become familiar with the ASP.NET MVC application development, we only need to follow the rules (such as the agreement with the type of directory structure and file naming, etc.) agreed definition of the appropriate type and View Controller file on it. When the ASP.NET MVC framework during the processing of the request, it parses the type of target generation parameter obtained according to the routing Controller, and then automatically creates and executes it Controller object. If the target Action method needs to render a View, the framework agreement will be to find the corresponding View file (.cshtml file) according to a predefined directory, and type it implements dynamic compilation to generate the corresponding. After creating goals out of the View object, it generates HTML will be executed after the reply to the client as a response. As can be seen, the entire request process reflected his " Framework Call application " Hollywood rules.

总的来说,我们在一个框架的基础上进行应用开发,就相当于在一条调试好的流水线上生产某种商品。我们只需要在相应的环节准备对应的原材料,最终下线的就是我们希望得到的产品。IoC几乎是所有框架均具有的一个固有属性,从这个意义上讲,“IoC框架”的说法其实是错误的,世界上并没有什么IoC框架,或者说所有的框架都是IoC框架

三、流程定制

我们采用IoC实现了流程控制从应用程序向框架的转移,但是被转移的仅仅是一个泛化的流程,任何一个具体的应用都可能需要对该流程的某些环节进行定制。还是以我们的MVC框架来说,默认实现的请求处理流程可以只考虑针对HTTP 1.1的支持,但是我们在设计框架的时候应该提供相应的扩展点来支持HTTP 2。作为一个Web框架,用户认证功能是必备的,但是框架自身不能限制于某一种或者几种固定的认证方式,它应该允许我们通过扩展实现任意的认证模式。

我们可以说得更加宽泛点。如下图所示,我们将一个泛化的工作流程(A=>B=>C)定义在框架之中,建立在该框架的两个应用需要对组成这个流程的某些环节进行定制。比如步骤A和C可以被App1重用,但是步骤B却需要被定制(B1)。App2则重用步骤A和B,但是需要按照自己的方式处理步骤C。

3-4

IoC将对流程的控制从应用程序转移到框架之中,框架利用一个引擎驱动整个流程的自动化执行。应用程序无需关心工作流程的细节,它只需要启动这个引擎即可。这个引擎一旦被启动,框架就会完全按照预先编排好的流程进行工作,如果应用程序希望整个流程按照自己希望的方式被执行,需要在启动之前对流程进行定制。一般来说,框架会以相应的形式提供一系列的扩展点,应用程序通过注册扩展的方式实现对流程某个环节的定制。在引擎被启动之前,应用程序将所需的扩展注册到框架之中。一旦引擎被正常启动,这些注册的扩展会自动参与到整个流程的执行过程中。

In summary, IoC on the one hand by the flow control from the application process itself to achieve reuse for the reversal of the frame , on the other hand to make this process to be reused by the built-in extension mechanisms can be customized freely , both factors determine the framework of their value. Let reuse framework not only provides a single API functionality is implemented as an application, but to provide solutions to a set of executable, so that we can customize the frame can be customized for different applications, which undoubtedly can be used to frame among the more applications.

[ASP.NET Core 3 frame Disclosure] dependency injection: Inversion of Control
[ASP.NET Core 3 frame Disclosure] dependency injection: the IoC mode
[ASP.NET Core 3 frame Disclosure] dependency injection: Dependency injection mode
[ASP.NET Core 3 framework Secret] dependency injection: a mini-version of the DI framework

Guess you like

Origin www.cnblogs.com/artech/p/inside-asp-net-core-03-01.html