ASP. Net core dependency injection details



ASP.NET CoreThe application will rely on various components to provide services during startup, and these components will be standardized in the form of interfaces. These components are what we call services,ASP.NET CoreThe framework is based on an underlying dependency injection framework, which uses containers to provide required services. To understand the dependency injection container and its mechanism, we need to understand what dependency injection is.

1、 Control reversal

When it comes to dependency injection, we have to mention inversion of control (IOC).
definition:High level modules should not rely on low-level modules, and both should rely on their abstractions; Abstractions should not depend on details; Details should depend on abstraction.
Compared with the variability of details, abstract things are much more stable. An architecture based on abstraction is much more stable than an architecture based on detail. stay.NETIn, abstraction refers to interfaces or abstract classes, and details refer to specific implementation classes. The purpose of using interfaces or abstract classes is to formulate specifications and contracts without involving any specific operations, and to entrust the task of showing details to their implementation classes.

2、 Hollywood law

“Don’t call us, we’ll call you(don‘t call us, we‘ll call you)”This is the famous Hollywood principle. In Hollywood, you have to go home and wait after submitting your resume to the performing arts company. Under the complete control of the entertainment company, the actors can only passively accept the assignment of the company and complete their own performances in the required links.IIOCBased on the Hollywood principle, all components are passive(Passive), all component initialization and invocation are the responsibility of the container.
withASP.NET MVCFor development, we only need to define the correspondingcontrollerandViewFile. The whole framework will resolve the parameters to the target according to the routing rulesController, if the targetActionMethod needs to render aView, the framework will find the correspondingViewDocuments(.cshtmlFile), dynamically compile it to generate HTML reply to the client, and the whole framework reflectsIoCIdeas.

3、 Process control

IoCIt is to migrate the process control from the application to the framework. The framework uses an engine to drive the automatic execution of the whole process. The application does not need to care about the details of the workflow. It just needs to start the engine. The framework will provide extension points in the form of tin, and the application can control a certain link by registering extensions. Once the engine (container) is started, the registered extension will automatically participate in the execution of the whole process.

It is not difficult to see the role IOC plays in the above figure.
Before use:The whole program depends on each other. When new requirements are put forward, it will affect the whole body. This is the last thing we want to see. We can sort out the relationship in small projects. When there are more and more requirements, it is simply unimaginable.
Start using:After the introduction of the third party, there is no coupling relationship between the modules, which minimizes the dependency, and all controls are centralized through IOC.
After use:To facilitate observation, after removing the IOC container in the middle, it can be seen that there is no coupling relationship between the modules. After modifying a single module, it is no longer necessary to consider other modules.

4、 Three dependency injection methods

1. constructor injection

Constructor injection is to inject the dependent object into the object created by the constructor with the help of parameters. Usually, the constructor is used to implement injection.

    public class A
        public IB B { get; }
        public A(IB b) => B = b;

ASP. Net core


    public class WeatherForecastController : ControllerBase
        private static readonly string[] Summaries = new[]
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
            _logger = logger;

        public IEnumerable<WeatherForecast> Get()
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]

2. attribute injection

By dimensioningInjectionAttributeAttribute can be set as a dependency attribute of automatic injection.

    public class A
        public IB B { get; set; }
        public IC C { get; set; }

3. method injection

Also by dimensioningInjectionAttributeProperty can be labeled as an injection method.

    public class A
        public IB B { get; }
        public Initialize(IB b) => B = b;

In addition to automatically calling the implementation during the service initialization process of the container, we can also use it to implement another more free method injection. This method is implemented inASP.NET CoreWide range of applications. stayASP.NET CoreCalled at startupStartupThe object completes the middleware registration, but it does not need to implement an interface when defining the startup type, so theConfigureMethod does not have a fixed declaration, but any dependent service can be registered to this method through the following method.


  public class Startup
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            if (env.IsDevelopment())
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebApplication1 v1"));



            app.UseEndpoints(endpoints =>

5、 Life cycle

Addsingleton lifecycle:Project start – project close is equivalent to only one static class
Addscoped lifecycle:Request start – request end all the objects obtained in this request are the same
Addtransient lifecycle:Request acquisition – (GC recycle – active release) the object acquired each time is not the same

be careful:becauseAddScopedThe object is created at the time of request, so it cannot beAddSingletonObject, or evenAddTransientObject.
Weight: AddSingleton→AddTransient→AddScoped

6、 Asp Self contained injection in net core

       public void ConfigureServices(IServiceCollection services)
            services.AddScoped<IA, A>;
            services.AddSingleton<IB, B>;
            services.AddTransient<IC, C>;
            services.AddSwaggerGen(c =>
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebApplication1", Version = "v1" });

be careful:ASP.Net CoreThe injection in is still relatively simple, but when there are more and more services, manual injection is more troublesome. I will introduce other IOC frameworks later.

This is about asp Net core dependency injection. This is the end of the detailed article. More related asp Net core dependency injection content, please search the previous articles of developeppaer or continue to browse the related articles below. I hope you can support developeppaer in the future!

Recommended Today

JS accurate calculation

var numA = 0.1; var numB = 0.2; alert( numA + numB ); 0.1 + 0.2 = 0.30000000000000004。Calculation accuracy error problem (related to binary). For the four arithmetic operations of floating-point numbers, almost all programming languages will have the problem of similar precision error. However, methods have been encapsulated in c++/c\c\java to avoid the problem […]