auraphp / Aura.Di

Dependency Injection System
MIT License
349 stars 63 forks source link

newCompiledInstance - unable to resolve lazyNew services with params #229

Closed tysonlemire closed 2 weeks ago

tysonlemire commented 2 weeks ago

The container fails to compile if a service within the config classes is defined using a lazyNew and a param.

Calling ContainerBuilder newCompiledInstance using the example for a config in the getting started docs causes an error.

To reproduce the issue, patch /tests/Fake/FakeLibraryConfig.php and then run the ContainerBuilderTest::testCompilationSerialization test.

use Aura\Di\Container;
use Aura\Di\ContainerConfig;

+class FakeService {
+    public function __construct(public string $foo)
+    {
+    }
+}
+
 class FakeLibraryConfig extends ContainerConfig
 {
     public function define(Container $di): void
     {
         parent::define($di);
         $di->set('library_service', (object) ['foo' => 'bar']);
+        $di->set('fake_service', $di->lazyNew(FakeService::class));
+        $di->params['fake_service']['foo'] = 'bar';
     }

     public function modify(Container $di): void

output:

ReflectionException: Class "fake_service" does not exist
/Users/tyson.lemire/7shifts/Aura.Di/src/Resolver/Reflector.php:80
/Users/tyson.lemire/7shifts/Aura.Di/src/Resolver/Reflector.php:101
/Users/tyson.lemire/7shifts/Aura.Di/src/Resolver/Resolver.php:364
/Users/tyson.lemire/7shifts/Aura.Di/src/Resolver/Resolver.php:340
/Users/tyson.lemire/7shifts/Aura.Di/src/Resolver/Resolver.php:310
/Users/tyson.lemire/7shifts/Aura.Di/src/ContainerBuilder.php:119
/Users/tyson.lemire/7shifts/Aura.Di/tests/ContainerBuilderTest.php:179
frederikbosch commented 2 weeks ago

The error is correct. Params expect a class name.

$di->params[YouShouldReferenceAClassNameHereNotAServiceName::class]['constructorParamOfReferencedClass'] = $di->lazyGet('something');
tysonlemire commented 2 weeks ago

Thank you for the quick resolution!