Skip to content

Instantly share code, notes, and snippets.

@zHaytam
Last active August 18, 2020 19:04
Show Gist options
  • Save zHaytam/c5b1c5eeaf2f915dd416ed1ae1fee75c to your computer and use it in GitHub Desktop.
Save zHaytam/c5b1c5eeaf2f915dd416ed1ae1fee75c to your computer and use it in GitHub Desktop.
public static class ServicesExtensions
{
public static void AddProxiedScoped<TInterface, TImplementation>(this IServiceCollection services)
where TInterface : class
where TImplementation : class, TInterface
{
services.AddScoped<TImplementation>();
services.AddScoped(typeof(TInterface), serviceProvider =>
{
var proxyGenerator = serviceProvider.GetRequiredService<ProxyGenerator>();
var actual = serviceProvider.GetRequiredService<TImplementation>();
var interceptors = serviceProvider.GetServices<IInterceptor>().ToArray();
return proxyGenerator.CreateInterfaceProxyWithTarget(typeof(TInterface), actual, interceptors);
});
}
}
// In ConfigureServices
services.AddProxiedScoped<IBlogService, BlogService>();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment