Skip to content

Instantly share code, notes, and snippets.

@havarnov
Created September 21, 2023 08:29
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 havarnov/ca3020a89cd77b7cca6dfc67ab07f6e7 to your computer and use it in GitHub Desktop.
Save havarnov/ca3020a89cd77b7cca6dfc67ab07f6e7 to your computer and use it in GitHub Desktop.
using System;
using System.Threading.Tasks;
using AspectCore.Configuration;
using AspectCore.DynamicProxy;
using Microsoft.Extensions.Logging;
var loggerFactory = LoggerFactory.Create(c => c.AddSimpleConsole());
var generator = new ProxyGeneratorBuilder()
.Configure(c =>
{
c.Interceptors.Add(
new TypeInterceptorFactory(
typeof(LoggerInterceptor),
new object[] { loggerFactory.CreateLogger("Foo") }));
})
.Build();
var actual = new Foo(loggerFactory.CreateLogger<Foo>());
var proxiedService = generator.CreateInterfaceProxy<IFoo>(actual);
await proxiedService.Bar(42);
public class LoggerInterceptor : AbstractInterceptor
{
private readonly ILogger _logger;
public LoggerInterceptor(ILogger logger)
{
_logger = logger;
}
public override async Task Invoke(AspectContext context, AspectDelegate next)
{
var parameters = string.Join(", ", context.Parameters);
_logger.LogInformation("START: {MethodName}: {Parameters}", context.ProxyMethod.Name, parameters);
await next(context); // Run the function
_logger.LogInformation("END: ");
}
}
public interface IFoo
{
Task<int> Bar(int input);
}
class Foo : IFoo
{
private readonly ILogger<Foo> _logger;
public Foo(ILogger<Foo> logger)
{
_logger = logger;
}
public async Task<int> Bar(int input)
{
_logger.LogInformation("INSIDE: Foo.Bar (start)");
await Task.Delay(TimeSpan.FromSeconds(1));
var result = input * 2;
_logger.LogInformation("INSIDE: Foo.Bar (end): {Result}", result);
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment