Skip to content

Instantly share code, notes, and snippets.

@ReallyLiri
Last active September 28, 2022 06:37
Show Gist options
  • Save ReallyLiri/c669c60db2109554d5ce47e03613a7a9 to your computer and use it in GitHub Desktop.
Save ReallyLiri/c669c60db2109554d5ce47e03613a7a9 to your computer and use it in GitHub Desktop.
ASP.NET dependency injection extensions
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
namespace ServiceCollectionExtensions
{
public static class ServiceCollectionExtensions
{
public static ConstructorInfo GetConstructor(this Type type)
{
var constructors = type.GetConstructors();
if (constructors.Length != 1)
{
throw new ArgumentException($"{type} doesn't have exactly one constructor");
}
var constructor = constructors[0];
return constructor;
}
public static IReadOnlyDictionary<string, object> ToPropertiesDictionary(this object obj)
=> new RouteValueDictionary(obj);
public static void AddSingletonWithConstructorParams<TService, TImplementation>(
this IServiceCollection services,
object paramsWithNames
) where TImplementation : class, TService where TService : class
=> services.AddSingletonWithConstructorParams(
typeof(TService),
typeof(TImplementation),
paramsWithNames
);
public static void AddSingletonWithConstructorParams(
this IServiceCollection services,
Type serviceType,
Type implementationType,
object paramsWithNames
)
{
if (paramsWithNames == null)
{
throw new ArgumentException("null argument");
}
if (!paramsWithNames.GetType()
.Name.Contains("AnonymousType"))
{
// due to ambiguous invocation of this method with a single arg
services.AddSingletonWithConstructorParams(
serviceType,
implementationType,
new[] {paramsWithNames}
);
return;
}
var constructor = implementationType.GetConstructor();
var overridingParams = paramsWithNames.ToPropertiesDictionary();
foreach (var parameterInfo in constructor.GetParameters())
{
if (overridingParams.ContainsKey(parameterInfo.Name))
{
var paramValue = overridingParams[parameterInfo.Name];
if (paramValue != null && !parameterInfo.ParameterType.IsInstanceOfType(paramValue))
{
throw new ArgumentException($"Argument of type {paramValue.GetType()} cannot be supplied as parameter named {parameterInfo.Name} for type {implementationType}");
}
}
}
AddSingletonWithParamsCallback(
services,
serviceType,
constructor,
parameterInfo => overridingParams.ContainsKey(parameterInfo.Name),
parameterInfo => overridingParams[parameterInfo.Name]
);
}
public static void AddSingletonWithConstructorParams<TService, TImplementation>(
this IServiceCollection services,
params object[] parameters
) where TImplementation : class, TService where TService : class
=> services.AddSingletonWithConstructorParams(
typeof(TService),
typeof(TImplementation),
parameters
);
public static void AddSingletonWithConstructorParams(
this IServiceCollection services,
Type serviceType,
Type implementationType,
params object[] parameters
)
{
var constructor = implementationType.GetConstructor();
if (parameters.Any(param => param == null))
{
throw new ArgumentException($"Cannot supply null ctor params to {nameof(AddSingletonWithConstructorParams)}");
}
var overridingValuesByParameterName = ConstructOverridingValuesByParameterName(constructor, parameters);
services.AddSingletonWithParamsCallback(
serviceType,
constructor,
parameterInfo => overridingValuesByParameterName.ContainsKey(parameterInfo.Name),
parameterInfo => overridingValuesByParameterName[parameterInfo.Name]
);
}
private static Dictionary<string, object> ConstructOverridingValuesByParameterName(ConstructorInfo constructor, params object[] parameters)
{
var overridingValuesByParameterName = new Dictionary<string, object>();
foreach (var parameterInfo in constructor.GetParameters())
{
var matchingOverridingParameters = parameters.Where(param => parameterInfo.ParameterType.IsInstanceOfType(param))
.ToList();
if (!matchingOverridingParameters.Any())
{
continue;
}
if (matchingOverridingParameters.Count > 1)
{
throw new ArgumentException($"More than one of the input parameters matches the ctor param {parameterInfo.Name} of type {parameterInfo.ParameterType}");
}
overridingValuesByParameterName[parameterInfo.Name] = matchingOverridingParameters[0];
}
return overridingValuesByParameterName;
}
private static void AddSingletonWithParamsCallback(
this IServiceCollection services,
Type serviceType,
ConstructorInfo constructor,
Predicate<ParameterInfo> parameterPredicate,
Func<ParameterInfo, object> parameterValueProvider
)
=> services.AddSingleton(
serviceType,
serviceProvider => InvokeConstructor(
constructor,
parameterPredicate,
parameterValueProvider,
serviceProvider
)
);
private static object InvokeConstructor(
ConstructorInfo constructor,
Predicate<ParameterInfo> parameterPredicate,
Func<ParameterInfo, object> parameterValueProvider,
IServiceProvider serviceProvider
)
=> constructor.Invoke(
constructor.GetParameters()
.Select(
parameterInfo => parameterPredicate(parameterInfo)
? parameterValueProvider(parameterInfo)
: serviceProvider.GetService(parameterInfo.ParameterType)
)
.ToArray()
);
public static TService GetRequiredServiceWithConstructorParams<TService, TImplementation>(this IServiceProvider serviceProvider, params object[] parameters) where TImplementation : TService where TService : class
{
var constructor = typeof(TImplementation).GetConstructor();
var overridingValuesByParameterName = ConstructOverridingValuesByParameterName(constructor, parameters);
return InvokeConstructor(
constructor,
parameterInfo => overridingValuesByParameterName.ContainsKey(parameterInfo.Name),
parameterInfo => overridingValuesByParameterName[parameterInfo.Name],
serviceProvider
) as TService;
}
public static void AddBuilder<TService, TImplementation, TArg>(this IServiceCollection serviceCollection) where TImplementation : class, TService where TService : class
=> serviceCollection.AddSingleton(
serviceProvider =>
{
return new Func<TArg, TService>(
arg => serviceProvider.GetRequiredServiceWithConstructorParams<TService, TImplementation>(arg)
);
}
);
}
}
@ReallyLiri
Copy link
Author

ReallyLiri commented Mar 19, 2020

Usage examples:

Say we have the following classes we want to register

public class Service1 : IService1
{
    public Service1(
        ILogger<Service1> logger,
        IDatabase database,
        IEncryption encryption,
        int intervalInMinutes,
        bool flush
    )
    {
        ...
    }

    ...
}

public class Service2 : IService2
{
    public Service2(
        ILogger<Service1> logger,
        IDatabase database,
        IEncryption encryption,
        int cacheSize,
        int featuresWeight
    )
    {
        ...
    }

    ...
}

We could register them as follows

public Task RunAsync(string name, string[] args)
    => new HostBuilder()
        .ConfigureHostConfiguration(...)
        .ConfigureAppConfiguration(...)
        .ConfigureServices(
            (hostContext, services) =>
            {
                var configuration = hostContext.Configuration;
                ConfigureServices(configuration, services);
            }
        )
        .ConfigureLogging(...)
        .Build()
        .RunAsyncSafe();

private void ConfigureServices(IConfiguration configuration, IServiceCollection services)
{
    services.AddSingleton<IDatabase, MyDatabase>();
    services.AddSingleton<IEncryption, MyEncryption>();

    services.AddSingletonWithConstructorParams<IService1, Service1>(60, false);

    services.AddSingletonWithConstructorParams<IService2, Service2>(new {cacheSize: 1024, featuresWeight: 17});
}

Then retrieving an instance would be as simple as

IServiceProvider serviceProvider = ...
var svc1 = serviceProvider.GetRequiredService<IService1>();

@TheYarin
Copy link

TheYarin commented Jul 4, 2020

that seems like an excellent wrapper! good job!

@Ewerton
Copy link

Ewerton commented Nov 18, 2021

What if we don't know the values of some parameters at application startup?
Imagine a scenario where each user is tied to an specific tenant, we only know the value of the tenant_id after the user logs-in.
How to register a dependency that needs to know the tenant_id?

@ReallyLiri
Copy link
Author

ReallyLiri commented Nov 19, 2021

What if we don't know the values of some parameters at application startup? Imagine a scenario where each user is tied to an specific tenant, we only know the value of the tenant_id after the user logs-in. How to register a dependency that needs to know the tenant_id?

For that you'd need to register a builder, i.e Func<TArg, TService>

Edit: I have some utils for that too, need to get them in order. Will update.

@ReallyLiri
Copy link
Author

@Ewerton I edited the gist, you can now use something like the following

serviceCollection.AddSingleton(
    svc => new Func<int, IMyService>(
        arg =>
            svc.GetRequiredServiceWithConstructorParams<MyImpl, IMyService>(arg)
    )
);

// ...

public SomeClass(Func<int, IMyService> builder) {
    var i = getInt();
    var my = builder(i);
}

See also AddBuilder, which you need to add for any number of args you want to support.

@CentrusB40
Copy link

@ReallyLiri
A definitely very good extension. I use this extension in the context of the interface IServices in Nuget package Microsoft.Extensions.DependencyInjection.
Only the extension with the AddBuilder<> I have not yet understood. Maybe someone/you can show me a simple example?

@ReallyLiri
Copy link
Author

@ReallyLiri A definitely very good extension. I use this extension in the context of the interface IServices in Nuget package Microsoft.Extensions.DependencyInjection. Only the extension with the AddBuilder<> I have not yet understood. Maybe someone/you can show me a simple example?

Thanks!
AddBuilder can be used when your service requires some dynamic or unknown value at registration time (i.e read from outside source, or recreated for each request with different config).
If you have a service MyService : IMyService, that accepts some interfaces in its constructor, along some long timeout, you could register serviceCollection.AddBuilder<IMyService, MyService, long>() and then consume it using Func<long, IMyService, which will create a new instance on each invocation, allowing you to inject all the non-long constructor parameters.
This is just a shortcut to registering the Func<> on your own like I referenced above to @Ewerton

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment