Created
February 1, 2017 00:14
-
-
Save Grinderofl/b646c58b2844afff591c3221913e2705 to your computer and use it in GitHub Desktop.
Castle Typed Factory for .NET Core
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"dependencies":{ | |
"Castle.Core": "4.0.0-beta002" | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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>()); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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