laravel依赖注入interface类报错Target [App\Services\UserRepositoryInterface] is not instantiable
问题呈现:Illuminate\Contracts\Container\BindingResolutionException thrown with message "Target [App\Services\UserRepositoryInterface] is not instantiable while building [App\Http\Controllers\HomeContro...
·
问题呈现:
Illuminate\Contracts\Container\BindingResolutionException thrown with message "Target [App\Services\UserRepositoryInterface] is not instantiable while building [App\Http\Controllers\HomeController]."
问题分析:
因为对laravel框架的架构还不是很熟悉,按照laravel技术文档的样例去实现interface依赖注入,因为文档上没有说明interface依赖注入需要将interface类和实体类绑定,所以漏掉了绑定这一步骤,因此报错如上。
问题解决:
可以自定义一个服务提供者(provider)也可以在已有的服务提供者(provider)里, 将实体类和interface类绑定即可。(注意)如果是自定义的provider,需要将provider类放到app.php配置文件中的providers选项中。
绑定代码放在provider中register方法中,具体如下:
public function register()
{
//
$this->app->bind('App\Services\UserRepositoryInterface', "App\Services\Relizes\UserRepository");
}
初学者遇到这个问题,问了度娘好久都没找到明确的解决方案,因此把它记录下来,方便以后遇到同样的问题可以查阅一下,也希望能帮到像我一样的小白,哈哈。
备注:最后的解决方案来自(https://blog.csdn.net/sweatott/article/details/55059633)
更多推荐
已为社区贡献3条内容
所有评论(0)