Skip to content

Instantly share code, notes, and snippets.

@wullemsb
Created March 23, 2024 12:11
Show Gist options
  • Save wullemsb/ef7eea17b2d3c95a1c3978a5f3b8b1ce to your computer and use it in GitHub Desktop.
Save wullemsb/ef7eea17b2d3c95a1c3978a5f3b8b1ce to your computer and use it in GitHub Desktop.
/// <summary>
/// Register all interfaces for a type.
/// </summary>
/// <returns>The original <see cref="T:Microsoft.Extensions.DependencyInjection.IServiceCollection" />.</returns>
public static IServiceCollection AsImplementedInterfaces(this IServiceCollection services)
{
var lastRegistration = services.LastOrDefault();
if (lastRegistration != null)
{
var implementationType = GetImplementationType(lastRegistration);
// We except that this method is called when a service is registered as a concrete type.
// If this is not the case, we bail out
if (lastRegistration.ServiceType != implementationType)
return services;
var interfaces = lastRegistration.ServiceType.GetInterfaces();
foreach (var @interface in interfaces)
{
// Register all interfaces proxying to our specific registration
services.Add(new ServiceDescriptor(
@interface,
provider => provider.GetService(implementationType),
lastRegistration.Lifetime));
}
return services;
}
return services;
}
private static Type? GetImplementationType(ServiceDescriptor descriptor)
{
if (descriptor.ImplementationType != null)
{
return descriptor.ImplementationType;
}
if (descriptor.ImplementationInstance != null)
{
return descriptor.ImplementationInstance.GetType();
}
if (descriptor.ImplementationFactory != null)
{
return descriptor.ImplementationFactory.GetType().GenericTypeArguments[1];
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment