Created
July 16, 2020 03:27
-
-
Save mahpah/84a9b3d21e604fc639a92b1512125afd to your computer and use it in GitHub Desktop.
Decorator pattern in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace | |
{ | |
public class DecoratorTests | |
{ | |
[Fact] | |
public void should_decorate_service() | |
{ | |
var services = new ServiceCollection(); | |
services.AddSingleton<MyService>(); | |
services.AddSingleton<IMyService, DecoratedMyService<MyService>>(); | |
var serviceProvider = services.BuildServiceProvider(); | |
var result = serviceProvider.GetService<IMyService>().DoTask(); | |
result.Should().Be("[Decorator] Task completed"); | |
} | |
} | |
public class DecoratedMyService<T> : IMyService where T : IMyService | |
{ | |
private readonly T _origin; | |
public DecoratedMyService(T origin) | |
{ | |
_origin = origin; | |
} | |
public string DoTask() | |
{ | |
return "[Decorator] " + _origin.DoTask(); | |
} | |
} | |
public class MyService : IMyService | |
{ | |
public string DoTask() | |
{ | |
return "Task completed"; | |
} | |
} | |
public interface IMyService | |
{ | |
string DoTask(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment