self::getContainer()->get cant get Autowired Service #45242
Replies: 5 comments
-
I think you need to make your service public: And some info about injecting services, but i think you know that. |
Beta Was this translation helpful? Give feedback.
-
@alessandro-podo Follow the instructions here: https://symfony.com/doc/current/testing.html#retrieving-services-in-the-test In particular you should be using static::getContainer instead of self::getContainer. And you might need to add your service to config/services_test.yaml. |
Beta Was this translation helpful? Give feedback.
-
Thanks for the answers. But I just wonder why it changed with the update to 6.0. |
Beta Was this translation helpful? Give feedback.
-
After some trial and error, I found the solution. is this with known behavior? |
Beta Was this translation helpful? Give feedback.
-
It's because all services private by default. See what is private services. You can't get private service from container like this $container->get(MyService::class); // <-- fail because it's private except if you describe this services as public in services.yaml For test you need services:
_defaults:
public: true # <-- this means that all services described in this file will be public by default and will be accessable by container->get
App\Factory\UserFactory: ~ # <-- will be accessable |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Symfony 5.4: works
$builder = self::getContainer()->get(EndPointBuilder::class);
Symfony 6.0.3: fail
$builder = self::getContainer()->get(EndPointBuilder::class);
Error:
Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: The "App\Service\CableLengthCalculator\Calculator" service or alias has been removed or inlined when the container was compiled. You should either make it public, or stop using the container directly and use dependency injection instead.
Did I miss something in the upgrade instructions?
Beta Was this translation helpful? Give feedback.
All reactions