Skip to content

Instantly share code, notes, and snippets.

@mahpah
Created July 16, 2020 03:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mahpah/84a9b3d21e604fc639a92b1512125afd to your computer and use it in GitHub Desktop.
Save mahpah/84a9b3d21e604fc639a92b1512125afd to your computer and use it in GitHub Desktop.
Decorator pattern in C#
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