Parameter injection for injected delegate #6397
Replies: 1 comment
-
I don't think there's anything built-in. OptionsBuilder<TOptions>.Configure<TDep>(Action<TOptions, TDep>) (docs, source) is a bit similar, though. I was thinking of something like this (untested): public static IServiceCollection AddTransientFunc<TArg, TDep, TService>(
this IServiceCollection services,
Func<TArg, TDep, TService> factory)
where TDep : class
{
return services.AddTransient<Func<TArg, TService>>(
(IServiceProvider sp) => TArg arg => factory(sp.GetRequiredService<TDep>(), arg));
}
services.AddTransientFunc<string, IDependency, IMyService>( (string key, IDependency dependency) =>
{
return new MyService(dependency, key);
}); But this has a problem: if you add more overloads with different numbers of arguments and dependencies, then how do you distinguish 2 arguments + 2 dependencies from 1 argument + 3 dependencies? Your proposed usage, where If this is only for creating new instances, and the constructor is public, then perhaps you can use ActivatorUtilities.CreateFactory (docs) so that the dependencies don't even need to be listed in the call. Untested: public static IServiceCollection AddTransientFunc<TArg, TService, TImplementation>(
this IServiceCollection services)
where TImplementation : TService
{
// Use the same ObjectFactory instance with every IServiceProvider.
ObjectFactory factory = ActivatorUtilities.CreateFactory(typeof(TImplementation), new[] { typeof(TArg) });
return services.AddTransient<Func<TArg, TService>>(
(IServiceProvider sp) => (TArg arg) => (TService)factory.CreateInstance(sp, new object[] { arg }));
}
services.AddTransientFunc<string, IMyService, MyService>(); dotnet/runtime#111228 would simplify that a bit. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
When injecting delegates, I use the below pattern:
Is there another way to require a service like minimal api?
Beta Was this translation helpful? Give feedback.
All reactions