Includes examples of service and usage.
With the service decorator you can extend the functionality for a service without touching the implementation.
The decorator design pattern follows the open/closed principle, which means classes are designed as open for extensions but closed for modifications.
Example service:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | [Litium.Runtime.DependencyInjection.Service(
ServiceType = typeof (IMyService),
Lifetime = Litium.Runtime.DependencyInjection.DependencyLifetime.Transient)]
public interface IMyService
{
string MyMethod();
}
internal class MyServiceImpl : IMyService
{
public string MyMethod()
{
return "world" ;
}
}
|
Usage:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public class DependencyInjectionExample
{
private readonly IMyService _myService;
public DependencyInjectionExample(IMyService myService)
{
_myService = myService;
}
public void Method()
{
string result = _myService.MyMethod();
}
}
|
When executing the Method() in the above example the resulting variable will contain the string "world".
A service decorator is an implementation class that implements the contract (abstract class or interface) and is registered with the Litium.Runtime.DependencyInjection.ServiceDecorator attribute.
In the constructor for the service decorator implementation you can inject the service that is decorated. Example:
1 2 3 4 5 6 7 8 9 10 11 12 | [Litium.Runtime.DependencyInjection.ServiceDecorator( typeof (IMyService))]
internal class MyService1Decorator : IMyService
{
private IMyService _parent;
public MyService1Decorator(IMyService parent){
_parent = parent;
}
public string MyMethod()
{
return "Hello " + _parent.MyMethod();
}
}
|
Executing the above example again will set the resulting variable to "Hello world".
It is possible to add another decorator for the same service. The decorators will be chained together.
1 2 3 4 5 6 7 8 9 10 11 12 | [Litium.Runtime.DependencyInjection.ServiceDecorator( typeof (IMyService))]
internal class MyService2Decorator : IMyService
{
private IMyService _parent;
public MyService2Decorator(IMyService parent){
_parent = parent;
}
public string MyMethod()
{
return _parent.MyMethod() + "!" ;
}
}
|
Executing the above example again will set the resulting variable to "Hello world!".
|