如何在服务类中使用EntityManager?

I am doing app where I need register user.

RegisterController

class RegisterController extends Controller
 {
   public function indexAction(Request $request){        
   }

   public function registerUserAction(Request $request) {
    $newUser = new Register();
    $newUser = $newUser->addNewUser($username, $password);
   }
 }

Service Register

class Register
 {
   public function addNewUser($username, $password) {
    if(self::validateUsername($username) && self::validatePassword($password)) {
    $em = $this->getDoctrine()->getManager();
    }
   }
}

config/services.yaml services:

_defaults:
    autowire: true     
    autoconfigure: true 
    public: false     
App\:
    resource: '../src/*'
    exclude: '../src/{Entity,Migrations,Tests}'
App\Controller\:
    resource: '../src/Controller'
    tags: ['controller.service_arguments']

Of course I can't access doctrine and entity manager in Register and I don't know how I can do this. Please don't post symfony documentation about service containers, I read it all and don't get it.

Start by injecting the entity manager into your Register service:

namespace App\Service;

use Doctrine\ORM\EntityManagerInterface;

class Register
{
    private $entityManager;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
    }
    public function addNewUser($username,$password)
    {
        $user = new User($username,$password);

        $this->entityManager->persist($user);

        return $user;
    }
}

Next, we take advantage of a somewhat unusual Symfony feature sometimes known as controller action injection:

namespace App\Controller;

use App\Service\Register;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class RegisterController
{
    public function registerUserAction(Request $request, Register $register)
    {
        $newUser = $register->addNewUser($username, $password);
        return new Response('Register Userx');
    }
}

And that is it. Symfony autowire takes care of connecting things up. Hopefully, this will make some of the service container documentation more understandable.