Scope

In applications that have multiple processes executing simultaneously, understanding service lifetime is very important to both functional and non-functional requirements. As illustrated in the previous unit test without the correct service lifetime, InventoryContext did not function as desired, and led to an invalid situation. Likewise, the incorrect use of service lifetimes could lead to applications that do not scale well. In general, the use of a lock-and-shared state should be avoided in multi-process solutions.

To illustrate this concept, imagine the FlixOne inventory management application was supplied to multiple staff members. The challenge now is how to perform a lock across multiple applications, and how to have a single collected state. In our terms, this would be a single InventoryContext class shared by multiple applications. Of course, this is where changing our solution to use a shared repository (for example, a database) would make sense, and/or changing our solution to a web application. We will cover databases and web application patterns in later chapters, but, as we are discussing service lifetimes, it does make sense to describe these in terms of a web application in more detail now.

The following diagram depicts a web app receiving two requests:

In terms of service lifetimes, a Singleton service lifetime will be available to both requests, while each request receives its own Scope lifetime. The important thing to note is around garbage collection. Dependencies that are created with a Transient service lifetime are marked to be released once the object is no longer referenced, while dependencies created with a Scope service lifetime are not marked to be released until the web request completes. And, dependencies created with a Singleton service lifetime are not marked to be released until the application ends.

Also, as shown in the following diagram, it is important to remember that dependencies in .Net Core are not shared between server instances in a web garden or web farm:

In the following chapters, different approaches to the shared state will be shown, including using a shared cache, databases, and other forms of repositories. 

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

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