[英]How can I inject a dependency quickly in Visual Studio?
While I was coding on an ASP.NET Core project, and I need some service in my action, like _tokenManager
, I have to add a new dependency injection, like this:当我在 ASP.NET Core 项目上编码时,我的操作中需要一些服务,比如_tokenManager
,我必须添加一个新的依赖注入,如下所示:
Adding a new dependency for a controller takes me at least 3 lines of code so it was not easy.为控制器添加一个新的依赖关系至少需要 3 行代码,所以这并不容易。 When I need several dependencies it will cost me lots of time.当我需要多个依赖项时,它会花费我很多时间。
BTW, while I was changing my code, some dependency may not be necessary and shall be removed.顺便说一句,当我改变我的代码时,一些依赖可能不是必需的并且应该被删除。 I have to check those dependencies one by one to make sure each of then is necessary.我必须一一检查这些依赖关系,以确保每一个都是必要的。 So is there any easy way to automatically add those dependencies when I try to use them and suggest me to remove those not necessary?那么有没有什么简单的方法可以在我尝试使用它们时自动添加这些依赖项并建议我删除那些不需要的依赖项?
It seems that Visual Studio already has this feature.好像 Visual Studio 已经有这个功能了。 How to enable this feature?如何启用此功能?
I got a solution.我有一个解决方案。
If you write your injected dependency first, like this:如果您首先编写注入的依赖项,如下所示:
public class MyController
{
private readonly MyDependency instance <Ctrl + . here>
public MyController()
{
}
}
Visual Studio won't give you suggestion to complete this. Visual Studio 不会给你建议来完成这个。
But if you write your dependency in your constructor first like this:但是,如果您首先像这样在构造函数中编写依赖项:
public class MyController
{
public MyController(
MyDependency instance <Ctrl + . here>
)
{
}
}
And Visual Studio 2019 will help you complete it.而 Visual Studio 2019 将帮助您完成它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.