[DI] Pass the requested type to the implementation factory to enable dynamic scenarios when the type isn't known statically
See original GitHub issueIs your feature request related to a problem? Please describe.
I’m trying to enable lazy injection of services, i.e. if I registered a service for IFoo
, I’d like to be able to inject a Lazy<IFoo>
or Func<IFoo>
. This is useful to solve circular dependency issues; Unity does this automatically. So I’d like to be able to do this:
services.AddTransient(typeof(Lazy<>), provider =>
{
...
});
However, in the factory delegate, I don’t have access to the requested type, so I can’t dynamically create a Lazy<T>
of the appropriate type.
Describe the solution you’d like
Having overloads of Add*
that accept a Func<IServiceProvider, Type, object>
would solve this. However it looks like it would be non-trivial, since the Func<IServiceProvider, object>
signature is used all the way down to the low-level implementation…
Alternatively, implementing lazy injection like in Unity would solve my immediate problem, but would be less extensible.
Describe alternatives you’ve considered
Using a third-party container like Unity. But I’d rather keep using the built-in DI container.
Additional context
N/A
Issue Analytics
- State:
- Created 5 years ago
- Reactions:4
- Comments:17 (2 by maintainers)
Top GitHub Comments
@pakrym this is literally one of the most critical features of a container
As much as I’d like it, I don’t think it will ever be implemented. The team’s position is quite clear: they don’t want to introduce a breaking change, and it’s already possible to do it by using a different container.
In the meantime, I have a solution for my initial problem (lazily resolved service):
Usage: