Services life cycle

A key point to master when we deal with dependency injection is the services life cycle. The services life cycle is an essential concept about performance, because a wrong service life cycle may cause complicated performance degradation. 

The object lifetime in .NET is simple: the object is instantiated, used, and finally disposed of by the garbage collector. The dispose phase is the most relevant in terms of performance. In a dependency injection process, the consumer of a specific dependency does not control its lifetime. Indeed, dependencies are usually initialized by the dependency injection container, and they continue to exist until all their consumers hold them.

A typical performance issue that engineers face in large applications is the memory leak. The garbage collector fails to clean objects because they are still referred to as consumers. Consequently, the memory of the server increases until it reaches saturation. It is not easy to find and solve these kinds of performance issues. In a .NET ecosystem, tools such as dotMemory can help you to analyze the instances of the objects that are created by your application, and eventually detect performance issues of this type.

Speaking of dependency injection, the default life cycle types in ASP.NET Core are transient, scoped, and singleton. Let's discuss them more in detail.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.128.199.162