concept Volatile Dependency in category dependency injection

appears as: Volatile Dependency
Dependency Injection

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

By requiring all callers to supply the Volatile Dependency as a parameter to the class’s constructor.

The Control Freak anti-pattern occurs every time you depend on a Volatile Dependency in any place other than a Composition Root. It’s a violation of the Dependency Inversion Principle that we discussed in section 3.1.2.

As an example, the Control Freak anti-pattern happens when you create a new instance of a Volatile Dependency by using the new keyword. The following listing demonstrates an implementation of the Control Freak anti-pattern.

Listing 5.1 A Control Freak anti-pattern example
public class HomeController : Controller
{
    public ViewResult Index()
    {
        var service = new ProductService();    #1  

        var products = service.GetFeaturedProducts();
        return this.View(products);
    }
}

#1   HomeController creates a new instance of the Volatile Dependency, ProductService, causing tightly coupled code.

Every time you create a Volatile Dependency, you explicitly state that you’re going to control the lifetime of the instance and that no one else will get a chance to Intercept that particular object. Although the new keyword is a code smell when it comes to Volatile Dependencies, you don’t need to worry about using it for Stable Dependencies.2