Trying to install NuGet package programmatically - Package.GetGlobalService returns null

737 Views Asked by At

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?

1

There are 1 best solutions below

4
On

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.