I don't know how you defined your service but example below works fine. Assuming that you're calling service from your controller.
services.yml
services:
application_backend.service.user:
class: Application\BackendBundle\Service\UserService
arguments:
- @router
Service class
namespace Application\BackendBundle\Service;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\RouterInterface;
class UserService
{
private $router;
public function __construct(
RouterInterface $router
) {
$this->router = $router;
}
public function create()
{
$user = new User();
$user->setUsername('hello');
$this->entityManager->persist($user);
$this->entityManager->flush();
return new RedirectResponse($this->router->generate('application_frontend_default_index'));
}
}
Controller
public function createAction(Request $request)
{
//.........
return $this->userService->create();
}
UPDATE
Although original answer above answers original question, it is not the best practise so do the following if you want a better way. First of all do not inject @router
into service and do the following changes.
// Service
public function create()
{
.....
$user = new User();
$user->setUsername('hello');
$this->entityManager->persist($user);
$this->entityManager->flush();
.....
}
// Controller
public function createAction(Request $request)
{
try {
$this->userService->create();
return new RedirectResponse($this->router->generate(........);
} catch (......) {
throw new BadRequestHttpException(.....);
}
}