Was this helpful? Support me via buymeacoffee.com and help me create lots more great content!

Fixing: ServiceNotFoundException - service or alias has been removed or inlined when the container was compiled

When writing unit tests for App\Helper\MyHelper I received the following error

Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException : The "App\Helper\MyHelper" 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.

This resulted from having created a service and trying to load it during a KernelTestCase, however, as I had not used the service within my code anywhere yet, Symfony removed the service from the container, hence the error above.

My KernelTestCase looked like something like this


<?php

declare(strict_types=1);

namespace Tests\App\Helper;

use App\Helper\MyHelper;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

class MyHelperTest extends KernelTestCase
{
    public function testResolve(): void
    {
        $helper = static::getContainer()->get(MyHelper::class);

        $outcome = $helper->resolve(...);

        static::assertEquals('... expected ...', $outcome);
    }
}

The resolution for this was to use the helper class in my code, so I used dependency injection to get the helper class into the service that needed it. The kernel test case then passed successfully as the helper was no longer being removed from the container.

Originally published at https://chrisshennan.com/blog/fixing-servicenotfoundexception-service-or-alias-has-been-removed-or-inlined-when-the-container-was-compiled