Al Berger
Al Berger

Reputation: 1068

How to obtain a reference to the Package object within VSPackage MSVS extension?

I'm creating in C# my first Visual Studio extension (VSPackage). I have two classes in it:

class MyPackage : Package
{
    ...
}

class SomeOtherClass
{
    ...
}

An object of SomeOtherClass is instantiated after the package is loaded and needs to get a reference to the MyPackage instance. Is there a way to obtain a reference to the MyPackage object other than passing it as a parameter in the constructor of SomeOtherClass?

Upvotes: 2

Views: 774

Answers (3)

coactivechris
coactivechris

Reputation: 73

I have voted up SergeyT's answer. Reasoning is this:

A VS Package is not just a class which you can instantiate like any other class. It is a special class which is loaded up by Visual Studio, and kept in memory as a Singleton. This Package is wired into various VS Events, and is meant to serve as a provider of functionality to the various parts of your overall extension.

Getting an instance of it is not the same as getting the actual package loaded up by Visual Studio.

To accomplish what you're after, you need to use code as SergeyT has suggested:

 var vsShell = (IVsShell) ServiceProvider.GlobalProvider.GetService(typeof(IVsShell));
        if(vsShell.IsPackageLoaded(MyPackageGuid, out var myPackage) 
           == Microsoft.VisualStudio.VSConstants.S_OK) { 
        _myPackage = (IMyPackage)myPackage;
        }

By doing this, you are ensured to get the one and only Package reference, rather than just an instance of the class.

Upvotes: 3

SergeyT
SergeyT

Reputation: 850

You can get a reference to any loaded VsPackage with IVsShell.IsPackageLoaded method.

Reference to IVsShell can be obtained using SVsServiceProvider imported using Import attribute of MEF infrastructure.

As well, you can use ServiceProvider.GlobalProvider to get a reference to IVsShell.

Upvotes: 2

user3439065
user3439065

Reputation: 840

If I understand your question is right, you can do something like:

class MyPackage : Package
{
    private static MyPackage _instance;
    public static MyPackage Instance
    { 
        get
        {
            if(_instance != null)
                _instance = new MyPackage();
             return _instance;
         }
     }
}

class SomeOtherClass
{
     void Whatever()
     {
           // use MyPackage.Instance
     }
}

But this can be reliable only if you need one instance of MyPackage throughout the application's life time. Otherwise, pass a new instance of MyPackage to SomeOtherClass.

edit: local variable _instance should also be static; I missed that.

Upvotes: -1

Related Questions