1

I'm trying to get the list of installed NuGet packages in my ASP.NET MVC application and I'm using NuGet.VisualStudio like this:

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);
}

For some reasons I've put above code in Global.asax.cs file, but componentModel is always null. Any idea what's wrong with it?

Mo Sadeghipour
  • 489
  • 8
  • 25

1 Answers1

0

For some reasons I've put above code in Global.asax.cs file, but componentModel is always null. Any idea what's wrong with it?

According to the IComponentModel Interface, you can notice that the icomponentModel is a Interface in the in Microsoft.VisualStudio.ComponentModelHost.dll, which is a Visual Studio SDK Reference. So if you use IComponentModel, you need the visual studio instance. Generally, it used in the visual Studio Integrate project.

Besides, when you dig into the class IsPackageInstalled:

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

You will need to pass the parameter project, but ASP.NET MVC project din't have any project object. So it seems that we could not use this method in the ASP.NET project in this situation.

If you want to install NuGet package programmatically, you can refer to How to programmatically install a NuGet package? for more detail info.

Leo Liu
  • 71,098
  • 10
  • 114
  • 135
  • According to the link, it needs a given `.csproj ` file, so could it be used in ASP.NET? – Mo Sadeghipour Aug 22 '17 at 04:28
  • Yes, I`m not debug all scripts in that link, but I debug the GetNugetPackage method in a C# console application after install the nuget.core package, and build it successfully. I guess all scrpts in that link should be work in the ASP.NET, because this method use the NuGet API instead of Visual Studio SDK. https://blog.nuget.org/20130520/Play-with-packages.html – Leo Liu Aug 22 '17 at 05:31
  • It doesn't work on ASP.NET, because it still needs project object – Mo Sadeghipour Aug 22 '17 at 08:05
  • @MohammadSadeghipour, Sorry, where are you find it needs project object in the accepted answer in this link:https://stackoverflow.com/questions/41803738/how-to-programmatically-install-a-nuget-package/41895490#41895490? – Leo Liu Aug 22 '17 at 08:19