When I use dependency injection, is it possible to instance an injection object only if code reach there?
Please check the following code. The code logic is just example, no logic meaning.
But the pain for me is: some of injections are pretty heavy, because IInjectionA
maybe needs IInjectionE,F,G,H,...
, and IInjectionB
may depend on IInjectionO,P Q...
, but I want to instance A,B,C only if the code reach them.
I call it Lazy Instancing
. My question are:
- Does the concept exist?
- Are there solutions to provide this?
- Do all DI frameworks support this by default?
- Is it an anti-pattern thinking?
Right now my project is using ASP.NET Core's default DI framework only.
Let's say all injections here are AddScoped
or AddTransient
public class MyDependency : IInjectionD
{
private readonly IInjectionA _injectionA;
private readonly IInjectionB _injectionB;
private readonly IInjectionC _injectionC;
public MyDependency(IInjectionA injectionA, IInjectionB injectionB, IInjectionC injectionC,....)
{
_injectionA = injectionA;
_injectionB = injectionB;
_injectionC = injectionC;
}
public Task DoAction()
{
if (DateTime.Now.Day == 1)
{
// is it possible to instance _injectionA only if code come here?
return _injectionA.DoAction();
}
if (DateTime.Now.Day == 2)
{
// is it possible to instance _injectionB only if code come here?
return _injectionB.DoAction();
}
if (DateTime.Now.Day == 3)
{
// is it possible to instance _injectionC only if code come here?
return _injectionC.DoAction();
}
return Task.FromResult(0);
}
}
Thanks a lot.