Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement ASP.NET Core dependency injection

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article focuses on "how to implement ASP.NET Core dependency injection". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to implement ASP.NET Core dependency injection.

1. Preface

An important idea in object-oriented design (OOD) is the principle of dependency inversion (DIP), which leads to platitudes such as dependency injection (DI), inversion of control (IOC) and its container. Beginners are easily confused by these concepts (including me). Before learning the Core dependency injection service Let's first take a look at the concepts of dependency inversion principle (DIP), dependency injection (DI), and inversion of Control (IOC), and then take a closer look at the Core dependency injection service.

two。 Dependency inversion principle (DIP)

The high-level module does not depend on the implementation of the low-level module, while the low-level module depends on the interface defined by the high-level module. Generally speaking, the high-level module defines the interface, while the lower-level module is responsible for the implementation.

two。 Dependency injection (DI) 2.1Dependencies (D)

Dependencies are created when one class needs the collaboration of another class to get the job done.

Example 1:

Public class MyDependency {public MyDependency () {} public Task WriteMessage (string message) {Console.WriteLine ($"MyDependency.WriteMessage called. Message: {message}"); return Task.FromResult (0);} public class IndexModel: PageModel {MyDependency _ dependency = new MyDependency (); public void OnGet () {_ dependency.WriteMessage ("IndexModel.OnGet created this message.");}}

From the above code, we can see that the output message of the IndexModel module must instantiate the MyDependency module, that is, the implementation of the IndexModel module business must rely on the MyDependency module, which is dependency.

2.2 injection (I)

According to the DIP design principle: the high-level module does not depend on the implementation of the low-level module, while the low-level module depends on the interface defined by the high-level module, so we define an interface for the high-level module to call, and the bottom module is responsible for the implementation.

Example 2:

Public interface IMyDependency {Task WriteMessage (string message);} public class MyDependency: IMyDependency {public MyDependency () {} public Task WriteMessage (string message) {Console.WriteLine ($"MyDependency.WriteMessage called. Message: {message} "); return Task.FromResult (0);} public class IndexModel: PageModel {IMyDependency _ dependency = new MyDependency (); public void OnGet () {_ dependency.WriteMessage (" IndexModel.OnGet created this message. ");}}

From the above code, we can see that when we call the OnGetAsync method of the IndexModel module, we instantiate the MyDependency class through the IMyDependency interface to achieve its method content, which is called control forward. But Master says that instead of creating the MyDependency class, we should let the caller pass it to you, so you use the constructor to let the outside world give you these two dependencies.

Example 3:

Public interface IMyDependency {Task WriteMessage (string message);} public class MyDependency: IMyDependency {private readonly ILogger _ logger; public MyDependency (ILogger logger) {_ logger = logger;} public Task WriteMessage (string message) {_ logger.LogInformation ("MyDependency.WriteMessage called. Message: {MESSAGE} ", message); return Task.FromResult (0);} public class IndexModel: PageModel {private readonly IMyDependency _ dependency; public IndexModel (IMyDependency dependency) {_ dependency = dependency;} public void OnGet () {_ dependency.WriteMessage (" IndexModel.OnGet created this message. ");}}

From the above code, you can see that the creation of dependencies is thrown to a third-party system (for example: Autofac,Unity container), which is also called IOC container. The process in which you are only responsible for using it and others throw it to you to rely on is understood as injection. Also known as control inversion (IOC). Note that the ILogger interface within the framework has been injected and there is no need to re-inject it manually.

2.3 IOC Container

The IOC container can be seen as the place responsible for managing dependencies in a unified manner. Autofac,Unity is common.

The container is only responsible for two things:

The relationship between the ● binding service and the instance

● acquires instances and manages them (creation and destruction)

3. The difference between dependency inversion principle (DIP) and Control inversion principle (IOC)

DIP is a software design principle that only tells you how high-level modules should depend on each other, but it doesn't tell us how to decouple interdependent modules. IOC is a kind of software design pattern, which tells us how to decouple modules. It provides abstraction for interdependent components and gives the acquisition of dependent (low-level module) objects to third-party systems (e.g. Autofac,Unity container) to control, that is, dependent objects are not directly obtained through new in the classes of dependent modules.

4.NET Core dependency injection (DI) service

As described above, you should have some understanding of the concepts of dependency inversion principle (DIP), dependency injection (DI), and control inversion (IOC). In the .NET Core, the core of DI is divided into two components: IServiceCollection and IServiceProvider.

IServiceCollection is responsible for registration

IServiceProvider is responsible for providing examples

Let's learn how NET Core relies on DI services.

Step 1: use the interface to implement dependency inversion. Define an IMyDependency service.

Public interface IMyDependency {Task WriteMessage (string message);}

Step 2: define the implementation class MyDependency of the IMyDependency service.

Public class MyDependency: IMyDependency {private readonly ILogger _ logger; public MyDependency (ILogger logger) {_ logger = logger;} public Task WriteMessage (string message) {_ logger.LogInformation ("MyDependency.WriteMessage called. Message: {MESSAGE}", message); return Task.FromResult (0);}}

Step 3: register the IMyDependency service with the service container.

Public void ConfigureServices (IServiceCollection services) {/ / enrollment limits the service lifetime to the lifetime of a single request. The next section will talk about the service lifetime services.AddScoped ();}

Step 4: inject the service into the constructor of the class that uses it. Call the IndexModel.OnGet method in HomeController to output the WriteMessage message.

Public class IndexModel: PageModel {private readonly IMyDependency _ dependency; public IndexModel (IMyDependency dependency) {_ dependency = dependency;} public void OnGet () {_ dependency.WriteMessage ("IndexModel.OnGet created this message.");}} private readonly IMyDependency _ iMyDependency;public HomeController (IMyDependency iMyDependency) {_ iMyDependency = iMyDependency;} public IActionResult Index () {IndexModel _ IndexModel = new IndexModel (_ iMyDependency); _ IndexModel.OnGet (); return View ();}

The WriteMessage log messages are as follows:

5. Default service container replacement

In the future, we will show how to replace the built-in container with other container examples, such as replacing a third-party Autofac container. We need to register the Autofac container in the Startup.ConfigureServices method as follows:

Public IServiceProvider ConfigureServices (IServiceCollection services) {/ / Add Autofac var containerBuilder = new ContainerBuilder (); containerBuilder.RegisterModule (); containerBuilder.Populate (services); var container = containerBuilder.Build (); return new AutofacServiceProvider (container);}

It is important to note that if you need to use a third-party container, Startup.ConfigureServices must return IServiceProvider. Then customize a module class configuration dependency, as follows:

Public class DefaultModule: Module {protected override void Load (ContainerBuilder builder) {builder.RegisterType () .As ();}

At run time, the application uses Autofac to parse types and inject dependencies.

At this point, I believe you have a deeper understanding of "how to implement ASP.NET Core dependency injection". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report