Dependency Injection within Initialization Modules

In the last article, I did not mention Initialization Modules. Those also do not support a constructor injection but Initialization Modules are different.

Initialization Modules are the part of the infrastructure which runs during site startup. Those do not run after startup anymore. So it is fine to step away from rules applied to other application code.

But then what are the good practices to resolve services in the Initialization Modules? Service locator is an anti-pattern, Injected<T> also is an anti-pattern (as it is hidden Service locator).

Episerver provides another service location in the Initialization Modules - a Locate property of the InitializationEngine:

public void Initialize(InitializationEngine context)
{
    var loader = context.Locate.ContentLoader();
    var anotherLoader = context.Locate.Advanced.GetInstance<IContentLoader>();
}

The Locate property is a ServiceLocationHelper. This helper has methods to get to the common Episerver services. The Advanced property of this helper is an instance of the IServiceLocator which can be used to locate other services.

Summary

While it would be better to have a constructor injection support in the Initialization Modules, it is fine to use provided service location mechanisms to resolve service instances.