腔内依赖性注射

问题描述 投票:0回答:1

我试图了解流明中的依赖注入

我要添加userService

{
    protected $userService;
    public function __construct(UserService $userService, $config)
    {
        $this->userService = $userService;
    }

在此应用:控制台/命令/Command2.php

    $server = app(Server::class, [$config]);

收到错误

在Container.php第993行中:无法解析依赖项,解析类App \ SocketServer \ Server中的[Parameter#1 [$ config]

php dependency-injection lumen
1个回答
0
投票

可以在服务提供商中配置带有参数的依赖关系。可以通过运行以下命令生成服务提供者:

php artisan make:provider UserServiceProvider

修改UserServiceProvider.php文件中的设置方法

    public function register()
    {
        $this->app->singleton(UserService::class, function ($app) {
            $config = ['debug' => true];
            return new UserService($config);
        });
    }

config/app.php中注册:

'providers' => [
    // Other Service Providers

    App\Providers\UserServiceProvider::class,
],

然后,Laravel将能够注入依赖项:

    protected $userService;
    public function __construct(UserService $userService)
    {
        $this->userService = $userService;
    }
© www.soinside.com 2019 - 2024. All rights reserved.