-
Notifications
You must be signed in to change notification settings - Fork 35
Home
The recommended approach to employing a DI container in a software system is that the Composition Root of the application be the single place where the container is touched directly.
Unfortunately, many applications can’t create everything at once at a single point in time as application starts up or at the beginning of each incoming web/WCF request because not everything is known at that moment. These applications need a way to create new instances using the Kernel at a later time. Preferably this is done without introducing a reference to the container's types (or worse the container Kernel itself) away from the Composition Root.
Another unfortunately common antipattern which can become prevalent in the face of these types of constraints is use of the Service Locator antipattern.
This is where factories come into play. Instead of injecting a Kernel into types that need to create new instances we instead have the Container generate an implementation of a suitable factory on the fly and inject an instance of it to fulfil the Abstract Factory interface required by the consuming component. This factory is responsible for creating the new instances (internally, opaquely using the Kernel to realize the goal). There are two key ways in which one can employ this mechanism:
- request a factory interface type (requires a
Bind<IService>().
....ToFactory(...)
registration) - request a
Func<...,T>
delegate orLazy<T>
type (these act in the same manner but without you introducing an explicitly named type into the system, and no explicitBind
ing is required))
Both mechanisms are handled by this extension.