Can the containter inject itself?

Hello!

I have a situation where I need to inject the DI container into a class that is constructed using the container. How would I configure the container to make it possible to inject itself?

use Yiisoft\Di\Container;
class MyClass
{
  public function __construct(Container $cont)
  {
     ...
  }
}

Oops yes, this is possible. Nevermind. ^^

you need to bind the container instance into itself

use Yiisoft\Di\Container;
$container = new Container();
// register the container instance into itself
$container->set(Container::class, $container);
$myClass = $container->get(MyClass::class);

use Yiisoft\Di\Container;
class MyClass
{
    public function __construct(Container $cont)
    {
        // you now have access to the container
    }
}

container can now inject itself when resolving MyClass

1 Like

Brilliant, thank you :+1: :+1: