【问题标题】:Trying to install NuGet package programmatically - Package.GetGlobalService returns null尝试以编程方式安装 NuGet 包 - Package.GetGlobalService 返回 null
【发布时间】:2018-01-29 11:22:06
【问题描述】:

我正在尝试在我的 ASP.NET MVC 应用程序中获取已安装 NuGet 包的列表,并且我正在使用 NuGet.VisualStudio,如下所示:

var componentModel = (IComponentModel)Package.GetGlobalService(typeof(SComponentModel));
IVsPackageInstallerServices installerServices = componentModel.GetService<IVsPackageInstallerServices>();
if (!installerServices.IsPackageInstalled(project, "TemplateBuilder"))
{
    var installer = componentModel.GetService<IVsPackageInstaller>();
    installer.InstallPackage("All", project, "TemplateBuilder", (System.Version)null, false);
}

由于某些原因,我将上面的代码放在Global.asax.cs 文件中,但componentModel 始终为空。 知道它有什么问题吗?

【问题讨论】:

  • var componentModel = (IComponentModel)Package.GetGlobalService(typeof(SComponentModel)); 更改为var bob = Package.GetGlobalService(typeof(SComponentModel)); var componentModel = (IComponentModel)bob; bob 是什么?是否为空?
  • 是的,代码bob 为空
  • 不,我以前读过。

标签: c# asp.net-mvc visual-studio nuget componentmodel


【解决方案1】:

由于某些原因,我将上面的代码放在 Global.asax.cs 文件中,但 componentModel 始终为空。知道它有什么问题吗?

根据IComponentModel Interface,您可以注意到icomponentModelMicrosoft.VisualStudio.ComponentModelHost.dll 中的一个接口,这是一个Visual Studio SDK 参考。所以如果你使用IComponentModel,你需要Visual Studio 实例。 一般在visual Studio Integrate项目中使用。

另外,当你深入课堂时IsPackageInstalled

bool IsPackageInstalled(global::EnvDTE.Project project, string id);

您需要传递参数 project,但 ASP.NET MVC 项目没有任何项目对象。所以在这种情况下,我们似乎无法在 ASP.NET 项目中使用这种方法。

如果您想以编程方式安装 NuGet 包,可以参考How to programmatically install a NuGet package? 了解更多详细信息。

【讨论】:

  • 根据链接,它需要一个给定的.csproj 文件,那么它可以在ASP.NET中使用吗?
  • 是的,我没有调试该链接中的所有脚本,但我在安装 nuget.core 包后在 C# 控制台应用程序中调试 GetNugetPackage 方法,并成功构建它。我猜该链接中的所有脚本都应该在 ASP.NET 中工作,因为这种方法使用 NuGet API 而不是 Visual Studio SDK。 blog.nuget.org/20130520/Play-with-packages.html
  • 它在 ASP.NET 上不起作用,因为它仍然需要项目对象
  • @MohammadSadeghipour,对不起,您在哪里发现它需要项目对象在此链接中接受的答案中:stackoverflow.com/questions/41803738/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-25
  • 1970-01-01
  • 2017-08-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多