Skip to content

Instantly share code, notes, and snippets.

@Grinderofl
Created February 1, 2017 00:14
Show Gist options
  • Save Grinderofl/b646c58b2844afff591c3221913e2705 to your computer and use it in GitHub Desktop.
Save Grinderofl/b646c58b2844afff591c3221913e2705 to your computer and use it in GitHub Desktop.
Castle Typed Factory for .NET Core
{
"dependencies":{
"Castle.Core": "4.0.0-beta002"
}
}
public static class ServiceCollectionExtensions
{
private static readonly IProxyGenerator ProxyGenerator = new ProxyGenerator(true);
public static IServiceCollection AddTypedFactory<T>(this IServiceCollection services, ServiceLifetime lifetime = ServiceLifetime.Transient) where T : class
{
services.TryAddSingleton<TypedFactoryInterceptor>();
services.Add(new ServiceDescriptor(typeof(T), CreateProxy<T>, lifetime));
return services;
}
public static T CreateProxy<T>(IServiceProvider serviceProvider) where T : class
=>
ProxyGenerator.CreateInterfaceProxyWithoutTarget<T>(
serviceProvider.GetRequiredService<TypedFactoryInterceptor>());
}
public class TypedFactoryInterceptor : IInterceptor
{
private readonly IServiceProvider _serviceProvider;
public TypedFactoryInterceptor(IServiceProvider serviceProvider)
{
if (serviceProvider == null) throw new ArgumentNullException(nameof(serviceProvider));
_serviceProvider = serviceProvider;
}
public void Intercept(IInvocation invocation)
{
invocation.ReturnValue = ActivatorUtilities.GetServiceOrCreateInstance(_serviceProvider, invocation.Method.ReturnType);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment