Skip to content

Instantly share code, notes, and snippets.

@ovicrisan
Created March 31, 2019 03:58
Show Gist options
  • Save ovicrisan/70b2feb25e111e551b27da57dee5df5a to your computer and use it in GitHub Desktop.
Save ovicrisan/70b2feb25e111e551b27da57dee5df5a to your computer and use it in GitHub Desktop.
.NET Core decorator pattern with DI and Scrutor
// .NET Core console application to test decorator pattern with DI and Scrutor
// in terminal / command prompt:
// dotnet add package Scrutor
// dotnet add package Microsoft.Extensions.DependencyInjection
using System;
using Microsoft.Extensions.DependencyInjection;
namespace ScrutorDecorator
{
class Program
{
static void Main(string[] args)
{
// Without DI + Scrutor
//IThing thing = new Thing();
// Or:
//IThing thing = new ThingDecorated(new Thing());
// With DI
var collection = new ServiceCollection();
// First, add our service to the collection.
collection.AddSingleton<IThing, Thing>();
// Then, decorate Thing with the ThingDecorated type.
// Comment out next line and get non-decorated instance
collection.Decorate<IThing, ThingDecorated>();
var serviceProvider = collection.BuildServiceProvider();
// When we resolve the IThing service, we'll get the following structure:
// Thing -> ThingDecorated
var thing = serviceProvider.GetRequiredService<IThing>();
thing.DoSomething(5);
thing.DoSomethingElse("me");
Console.WriteLine("Press any key to continue....");
Console.ReadKey();
}
}
public interface IThing
{
void DoSomething(int n);
void DoSomethingElse(string name);
}
public class Thing: IThing
{
public void DoSomething(int n)
{
Console.WriteLine("DoSomething(): {0} + 1 = {1}", n, n + 1);
}
public void DoSomethingElse(string name)
{
Console.WriteLine("DoSomethingElse() called by {0}", name);
}
}
public class ThingDecorated : IThing
{
private readonly IThing _thing;
public ThingDecorated(IThing thing)
{
_thing = thing;
}
public void DoSomething(int n)
{
_thing.DoSomething(n);
Console.WriteLine("DoSomething() finished.");
}
public void DoSomethingElse(string name)
{
_thing.DoSomethingElse(name);
Console.WriteLine("DoSomethingElse() finished");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment