0

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:

  1. Does the concept exist?
  2. Are there solutions to provide this?
  3. Do all DI frameworks support this by default?
  4. 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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Dongdong
  • 2,208
  • 19
  • 28
  • `some of injections are pretty heavy` why they are heavy? They are just initialising. – Rabban Nov 04 '19 at 16:49
  • On the surface, it sounds like your DI tree is unnecessarily complicated, but the best you can hope for is probably going to be something like [this](https://stackoverflow.com/questions/44934511/does-net-core-dependency-injection-support-lazyt). – DavidG Nov 04 '19 at 16:49

0 Answers0