在 Symfony 中默认机制之外的机制中启用依赖注入

我的 Symfony 应用程序中有一个机制,我需要基于默认服务容器启用依赖注入。HttpKernel我在此处通过控制器机制管理依赖注入的地方找到了代码(在 Sourcegraph 上浏览)。


但是,我不确定如何实例化ArgumentResolver用于此目的的 。


以下是我到目前为止尝试过的:


class DataSourceController

{

  public function queryDatasource(string $hash, Request $request, ArgumentResolverInterface $argument_resolver)

  {

    // Logic to construct the $datasource variable


    $arguments = $argument_resolver->getArguments($request, [$datasource, 'query']);


    $data = $datasource->query(...$arguments);


    return new JsonResponse($data);

  }

}

但是,似乎ArgumentResolverInterface无法自动连接,我不确定应该如何处理。那么如何实例化 的子类ArgumentResolverInterface,或者我应该使用什么其他机制在我的应用程序的任意组件中实现依赖注入?


白衣染霜花
浏览 80回答 1
1回答

MMMHUHU

经过更多的研究和扫描 Symfony 的源代码后,我找到了一个适合我需要的解决方案:我手动创建了一个实例ArgumentResolver并使用它。注意我的用例需要解析一个不是服务的对象,因此它不能像任何其他服务一样通过依赖注入机制来解析。我将其包含在我的答案中,因为它可能对其他人有用:$resolvers = [];array_push($resolvers, ...ArgumentResolver::getDefaultArgumentValueResolvers());array_push($resolvers, new class implements ArgumentValueResolverInterface {  // implement the interface to resolve an argument with a specific type/name});$argument_resolver = new ArgumentResolver(new ArgumentMetadataFactory(), $resolvers);// to use it:$arguments = $argument_resolver->getArguments($request, [$datasource, 'query']);$datasource->query(...$arguments);我希望这对其他人有用。我无法证明这是解决方案或最佳解决方案,但它似乎对我的用例有用。我欢迎其他人发表评论/回答,以便我们共同改进解决方案
打开App,查看更多内容
随时随地看视频慕课网APP