Dependency injection
Dependency injection is a pattern that implements inversion of control for resolving dependencies into services. A dependency is one or many parameters that exist in the service constructor.
When the service is created the dependency injection will find the correct implementation of the dependency for each constructor parameter. The created service doesn’t need to know anything about the implementation of the dependency and the implementation can easily be replaced inside the dependency container to use another implementation without any need to update the usage.
Dependency injection can be used with service contract or implementation. A service contract is the preferred way.
A dependency can be registered as 3 different types:
- Singleton - one instance is created of the implementation and used for all dependencies.
- Transient - create a new instance for all dependencies.
- Scope - create a new instance in each scope. Reuse the instance in the scope for all dependencies. A scope is a specified with a start and stop.
- For web sites a scope is created for each request.
- For a scheduled task a scope is created for each execution.
The registration is done with the Litium.Runtime.DependencyInjection.Service attribute with which you decorate the service contract or service implementation.
A service factory can be used to create a service that depend on parameters in the request.
Named services are used when you have multiple instances of the same implementation and decide which instance to use during runtime.
The Decorator design pattern follows the open/closed principle, which means classes are designed as open for extensions but closed for modifications.