Skip to content

Instantly share code, notes, and snippets.

internal interface IExampleService
{
Task VeryImportantWorkAsync(int additionalSecondsToWait);
}
internal sealed class ExampleService : IExampleService
{
private readonly IImportantDataProvider _dataProvider;
public ExampleService(IImportantDataProvider dataProvider)
internal interface IImportantDataProvider
{
TimeSpan GetTimeToWait();
}
internal sealed class ImportantDataProvider : IImportantDataProvider
{
/// <inheritdoc />
public TimeSpan GetTimeToWait() => TimeSpan.FromSeconds(2);
}
internal sealed class ExampleServiceClassicDecorator : IExampleService
{
private readonly IExampleService _decorated;
private readonly ILogger<ExampleServiceClassicDecorator> _logger;
public ExampleServiceClassicDecorator(IExampleService decorated,
ILogger<ExampleServiceClassicDecorator> logger)
{
_decorated = decorated;
public static IServiceCollection Decorate<TInterface, TDecorator>(this IServiceCollection services)
where TInterface : class
where TDecorator : class, TInterface
{
var objectFactory = ActivatorUtilities.CreateFactory(
typeof(TDecorator),
new[] { typeof(TInterface) });
// Save all descriptors that needs to be decorated into a list.
var descriptorsToDecorate = services
void ConfigureServices(IServiceCollection services)
{
services
.AddLogging(configure =>
{
configure.AddConsole();
configure.SetMinimumLevel(LogLevel.Information);
})
.AddSingleton<IImportantDataProvider, ImportantDataProvider>()
.AddSingleton<IExampleService>(sp =>
public void ConfigureServices(IServiceCollection services)
{
services
.AddLogging(configure =>
{
configure.AddConsole();
configure.SetMinimumLevel(LogLevel.Information);
})
.AddSingleton<IImportantDataProvider, ImportantDataProvider>()
.AddSingleton<IExampleService, ExampleService>()
internal class DispatchProxyEmptyDecorator<TDecorated> : DispatchProxy
{
private TDecorated _decorated;
protected override object Invoke(MethodInfo targetMethod, object[] args)
{
var result = targetMethod.Invoke(_decorated, args);
return result;
}
internal class DispatchProxyMinimalLoggingDecorator<TDecorated> : DispatchProxy
{
private TDecorated _decorated;
private ILogger<DispatchProxyLoggingDecorator<TDecorated>> _logger;
protected override object Invoke(MethodInfo targetMethod, object[] args)
{
try
{
internal class DispatchProxyLoggingDecorator<TDecorated> : DispatchProxy
{
private TDecorated _decorated;
private ILogger<DispatchProxyLoggingDecorator<TDecorated>> _logger;
protected override object Invoke(MethodInfo targetMethod, object[] args)
{
try
{
internal static class ServiceCollectionsExtensions
{
public static IServiceCollection DecorateWithDispatchProxy<TInterface, TProxy>(this IServiceCollection services)
where TInterface : class
where TProxy : DispatchProxy
{
MethodInfo createMethod;
try
{
createMethod = typeof(TProxy)