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

Case Analysis of ASP.NET Core dependency injection

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

Share

Shulou(Shulou.com)05/31 Report--

Today, the editor will share with you the relevant knowledge points of ASP.NET Core dependency injection case analysis, the content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.

The underlying design of ASP.NET Core supports and uses dependency injection. ASP.NET Core applications can use built-in framework services to inject services into methods that start classes, and application services can also be configured for injection. The default service container provided by ASP.NET Core provides a minimum feature set and is not a substitute for other containers.

1. On dependency injection

Dependency injection (Dependency injection,DI) is a technique that implements loose coupling between objects and dependents, providing these objects that a class uses to perform its operations to the class as injection, rather than directly instantiating dependencies or using static references. In general, classes allow them to follow the principle of display dependency through constructor declarator 2 dependencies. This method is called constructor injection.

When classes are designed with the idea of DI, their coupling is looser because they do not rely on their collaborators to hard code directly. This follows the principle of dependency inversion, which states that high-level modules should not rely on underlying modules: both rely on abstractions.

Classes require that they be provided with abstraction (usually an interface) when they are constructed, rather than referencing a specific implementation. Extracting the dependencies of the interface and providing the implementation of the interface as parameters is also an example of the Policy Design pattern.

When a class is used to create a class and its associated dependencies, this becomes a containers, or an Inversion of Control, IoC container, or a dependency injection container. The container is essentially a factory that provides an instance of the type requested from it. If a given type declares that it has dependencies and the container has been configured to provide dependencies, it will create dependencies as part of creating a request instance. In addition to creating object dependencies, the container usually manages the life cycle of the objects in the application.

ASP.NET Core contains a simple built-in container that supports constructor injection by default. The container of ASP.NET refers to the type services it manages, and the service of the built-in container can be configured in the ConfigureServices method of the Startup class.

two。 Use the services provided by ASP.NET Core

The ConfigureServices method of the Startup class is responsible for defining the services that the application will use, including features that come with the platform, such as Entity Framework Core and ASP.NET Core MVC. In addition to several services provided by IServiceCollection, you can use some extension methods (AddDbContext,AddMvc,AddTransient, etc.) to add and register additional services with the container:

Public void ConfigureServices (IServiceCollection services) {services.Configure (options = > {/ / This lambda determines whether user consent for non-essential cookies is needed for a given request. Options.CheckConsentNeeded = context = > true; options.MinimumSameSitePolicy = SameSiteMode.None;}); services.AddMvc (). SetCompatibilityVersion (CompatibilityVersion.Version_2_2); services.AddDbContext (options = > options.UseSqlServer (Configuration.GetConnectionString ("DefaultConnection"), providerOptions = > providerOptions.EnableRetryOnFailure ()); services.AddTransient ();}

The functions and middleware provided by ASP.NET Core follow the convention to use a single AddService extension method to register all the services required for this function.

3. Register for your own service

We can register our services according to services.AddTransient ();. The first paradigm type represents the type (usually an interface) that will be requested from the container. The second paradigm type represents the specific type that will be instantiated by the container and used to complete the request.

The AddTransient method is used to map an abstract type to a concrete service instantiated separately for each object that needs it. It is important to choose the appropriate life cycle for each service that is registered, which will be described later.

The following is an example of registering your own service:

1. Interface public interface IAccountServices {Task GetList ();} 2. The implementation class public class AccountServices:IAccountServices {AccessManagementContext _ context; public AccountServices (AccessManagementContext context) {_ context = context;// injects} public async Task GetList () {try {var query = _ context.Account.ToListAsync (); return query into the constructor. } catch (Exception ex) {return null;}} 3. Register the custom service and EF context AccessManagementContextpublic void ConfigureServices (IServiceCollection services) {services.AddMvc () .SetCompatibilityVersion (CompatibilityVersion.Version_2_2) in ConfigureServices; services.AddDbContext (options = > options.UseSqlServer (Configuration.GetConnectionString ("DefaultConnection"), providerOptions = > providerOptions.EnableRetryOnFailure ()); services.AddTransient ();} 4. Dependency injection public class AccountController in the Controller constructor: Controller {private IAccountServices _ accountServices; public AccountController (IAccountServices accountServices) {_ accountServices = accountServices;} / / GET: Account public async Task Index () {var vms = await _ accountServices.GetList (); return View (vms);} 4. Lifecycle and registration options for the service

ASP.NET service lifecycle:

1.Transient instantaneous

Transient lifecycle services are created each time they request. Suitable for lightweight, stateless services.

2.Scoped scope

The Scoped lifecycle is created once per request.

3.Singleton singleton

Singleton lifecycle services are created on their first request, and each subsequent request uses the same instance.

The service can be registered in the container in a variety of ways, and in addition to the previous registration method, you can also specify a factory that will be used to create the desired instance. Other registration methods will be described in more detail later.

Here is a simple example of each lifecycle:

1. Create the interface: namespace MVCTest.Interfaces {public interface IOperation {/ unique ID / Guid OperationId {get;}} public interface IOperationTransient: IOperation {} public interface IOperationScoped: IOperation {} public interface IOperationSingleton: IOperation {} public interface IOperationInstance: IOperation {}} 2. Implementation class / public class Operation: IOperation, IOperationTransient, IOperationScoped, IOperationSingleton, IOperationInstance {public Operation () {OperationId = Guid.NewGuid ();} public Operation (Guid operationId) {if (operationId = = null) {OperationId = Guid.NewGuid () } OperationId = operationId;} public Guid OperationId {get;} 3. Register to container public void ConfigureServices (IServiceCollection services) {services.AddTransient (); services.AddScoped (); services.AddSingleton (); services.AddSingleton (); services.AddTransient (); services.AddMvc (). SetCompatibilityVersion (CompatibilityVersion.Version_2_1);} 4. OperationServices is also registered to test the singleton pattern (all requests in the singleton lifecycle service use the service instantiated for the first time) and the scope lifecycle service is created only once per request, no matter how many places the instance public class OperationServices {public IOperationTransient OperationTransient {get;} public IOperationScoped OperationScoped {get;} public IOperationSingleton OperationSingleton {get;} public IOperationInstance OperationInstance {get } public OperationServices (IOperationTransient operationTransient, IOperationScoped operationScoped, IOperationSingleton operationSingleton, IOperationInstance operationInstance) {OperationTransient = operationTransient; OperationScoped = operationScoped; OperationSingleton = operationSingleton; OperationInstance = operationInstance;} 5. Use public class OperationController in Controller: Controller {public IOperationTransient OperationTransient {get;} public IOperationScoped OperationScoped {get;} public IOperationSingleton OperationSingleton {get;} public IOperationInstance OperationInstance {get;} public OperationServices _ operationServices; public OperationController (IOperationTransient operationTransient, IOperationScoped operationScoped, IOperationSingleton operationSingleton, IOperationInstance operationInstance, OperationServices operationServices) {OperationTransient = operationTransient OperationScoped = operationScoped; OperationSingleton = operationSingleton; OperationInstance = operationInstance; _ operationServices = operationServices;} / / GET: Operation public ActionResult Index () {ViewBag.OperationTransient = OperationTransient; ViewBag.OperationScoped = OperationScoped; ViewBag.OperationSingleton = OperationSingleton; ViewBag.OperationInstance = OperationInstance; ViewBag._operationServices = _ operationServices Return View ();}} 6.Index displays @ {ViewData ["Title"] = "Index" } Controller Operations OperationTransient: @ ViewBag.OperationTransient.OperationId OperationScoped: @ ViewBag.OperationScoped.OperationId OperationSingleton: @ ViewBag.OperationSingleton.OperationId OperationInstance: @ ViewBag.OperationInstance.OperationId Services Operations OperationTransient: @ ViewBag._operationServices.OperationTransient.OperationId OperationScoped: @ ViewBag._operationServices.OperationScoped.OperationId OperationSingleton: @ ViewBag._operationServices.OperationSingleton.OperationId OperationInstance: @ ViewBag._operationServices.OperationInstance.OperationId7. Running result

As you can see, the identity of the singleton lifecycle service is the same for each request. The scope lifecycle service, the same instance used in one request, and the second request to create a new instance.

5. Request service

In an ASP.NET request from HttpContext, the available services are exposed through the RequestServices collection.

The requesting service describes your configured services and requests as part of the application. After the child objects specify dependencies, the objects that meet the requirements can be found by looking for the corresponding types in RequestServices, rather than ApplicationServices.

6. Design dependency injection service

In custom services, avoid using static methods and directly instantiating dependent types, but request it through dependency injection. (New is Glue)

If a class has too many dependencies injected, it usually indicates that your class is trying to do too much (violating the single responsibility principle) and needs to transfer some responsibilities.

Similarly, the Controller class should focus on UI, so details such as business logic and data access should be in other classes.

These are all the contents of the article "ASP.NET Core dependency injection case Analysis". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

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