concept Release in category .net

appears as: Release
Dependency Injection in .NET

This is an excerpt from Manning's book Dependency Injection in .NET.

A DI CONTAINER should be used in three successive phases called Register, Resolve, and Release. Table 3.3 describes each of the phases in more detail.

Figure 8.4. All of the CommerceServiceContainer class’s implementation currently resides in the ResolveProductManagementService method. The Release method does absolutely nothing, and there are no fields or properties on the class. If you’re wondering why we have the Release method, we’ll get to it in section 8.2.2.

If you refer back to listing 7.7, you’ll notice that the IInstanceProvider implementation already calls the Release method on the container. So far, you haven’t implemented this method, relying on the garbage collector to do the job; but with disposable DEPENDENCIES it’s essential that you grasp this opportunity to clean up. Here’s the implementation.

Listing 8.5. Releasing disposable DEPENDENCIES

Because the Release method accepts any type of object, you first need a Guard Clause to make sure that instance is an IProductManagementService.

Concurrent threads may invoke the Release method simultaneously, so once more you must serialize access to the repositories dictionary to ensure that concurrent threads don’t corrupt its state. It could lead to memory leaks if repositories aren’t removed from the dictionary.