4.6. net core dependency injection encapsulation, 4.6 core

Source: Internet
Author: User

4.6. net core dependency injection encapsulation, 4.6 core

Nowadays, popular systems generally adopt the implementation of dependency injection, and use DI containers to directly obtain the instances of the classes/interfaces used .. . Net core also adopts the DI method, provides the interface IServiceCollection of DI containers, and provides the default implementation ServiceCollection based on this interface.

In this way, we can no longer introduce third-party DI components, such as Untiy, Autofac, and Castle.

In the implementation of ServiceCollectionExtensions of. net core source code, three registration methods are available: AddScoped, AddSingleton, and AddTransient. These three options (Singleton, Scoped, and Transient) reflect three forms of control over the service object lifecycle.

  • Singleton: the service instance created by ServiceProvider is stored on the ServiceProvider that serves as the root node. all serviceproviders with the same root node provide the same service instance. Suitable for Singleton mode.
  • Scoped: the service instance created by ServiceProvider is saved by itself. Therefore, the service instance provided by the same ServiceProvider object is the same object. You can simply think of it as an instance for each Request.
  • Transient: ServiceProvider always creates a new service instance for each service request. A lightweight, stateless service is created upon each access.

This is too much to say. Check the relevant materials. J

 

With the DI container, we can simply write the registration statement in the Startup. cs program. The following uses the operation log storage class as an example:

1         public void ConfigureServices(IServiceCollection services)2         {3             services.AddScoped<IOperLogRepository, OperLogRepository>();4         }

The first generic type indicates the type requested from the container (usually an interface ). The second generic type indicates the specific type that will be instantiated by the container and used to complete these requests.

 

When the logic service class of operation logs uses the warehouse of operation logs, we write as follows:

 1     public partial class OperLogAppService : IOperLogAppService 2     { 3         private IOperLogRepository service; 4  5         public OperLogAppService(IOperLogRepository service) 6         { 7             this.service = service; 8         } 9 10         public void Write(OperLogDto operLogDto)11         {12             this.service.Insert(operLogDto.AsInfo());13         }14     }

 

When you create an OperLogAppService instance, the system automatically creates an IOperLogRepository instance that registers the OperLogRepository class in the DI container.

However, this method is inconvenient in the framework. We know that the framework requires scalability and configuration. When adding system function modules, you also need to manually modify the program at Startup. add registration in the zooaeservice of cs (even if all registration is moved to an independent method), just like the first code written, including the registration warehousing class and registration logic service class. Compile and then publish and run the program. Every time a module is added or modified, the entire system needs to be compiled and released, which has a great impact on the running system.

Our practice is that each function module has a self-registered class. This self-registration class registers all the warehousing classes and logic service classes in the function module into the DI container. Startup. cs will automatically search for the self-registration classes in all functional modules, and then register the relevant content into the DI container. In this way, you only need to copy the application Assembly Dll of this module to the running directory of the system.

Based on the above ideas, we should first create a self-registered class. This class abstracts an interface IServiceRegister

1 public interface IServiceRegister2 {3 /// <summary> 4 // Register 5 /// </summary> 6 void Register (IServiceCollection services); 7}

 

 

We use a general module as an example. The self-registered class should be like this.

 1     public class CommonServiceRegister : IServiceRegister 2     { 3         public void Register(IServiceCollection services) 4         { 5             services.AddDbContext<CommonDbContext>(option => option.UseDb<CommonDbContext>(services.BuildServiceProvider()), ServiceLifetime.Scoped); 6  7             services.AddScoped<IParaReferRepository, ParaReferRepository>(); 8             services.AddScoped<IParaReferAppService, ParaReferAppService>(); 9             services.AddScoped<ISystemParameterRepository, SystemParameterRepository>();10             services.AddScoped<ISystemParameterAppService, SystemParameterAppService>();11 …12         }13     }

 

In this class, service. repliccoped registers the implementation class corresponding to the warehouse layer and logic layer interfaces. Here we only list the registration of system parameters and reference parameters. For the first sentence AddDbContext, see Access Components of 4.4 heterogeneous and multi-database

To. in cs, it is relatively simple to find and call these registration classes by yourself. The program is as follows: Call the GetSubTypes method of ReflectionHelper to obtain all implementation classes that inherit IServiceRegister. For each implementation class, create an instance and register the module's warehousing and logic services to the DI container. For the GetSubTypes method of ReflectionHelper, see: 4.1 reflection Tool

1     IEnumerable<Type> serviceList = ReflectionHelper.GetSubTypes<IServiceRegister>();2     foreach (Type type in serviceList)3     {4         IServiceRegister register = ReflectionHelper.CreateInstance(type) as IServiceRegister;5 6         register.Register(services);7     }

 

.. Net framework can also be implemented according to the above ideas, the difference is. net framework does not have startup. cs, you only need to write the above content into global. asax. The other difference is IServiceCollection. You can use DI containers provided by DI components such as Unity.

Cloud-oriented. net core development framework

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.