共用方式為


Getting an instance of Microsoft.VisualStudio.OLE.Interop.IServiceProvider from a Visual Studio AddIn

 

 

Last week I was working on an AddIn and I needed an instance of IServiceProvider. The closest I found was this piece of code:

EnvDTE.Project project;

IServiceProvider serviceProvider = new ServiceProvider(project.DTE as Microsoft.VisualStudio.OLE.Interop.IServiceProvider);

So after messing around and trying to get an instance of Project I saw the light and noticed that it's just pulling out the instance of DTE from project. So instead of having to get the active solution and figuring out how which was the active project we can simply cast _applicationObject to a IServiceProvider

 

From the auto generated code on OnConnection we get:

_applicationObject = (DTE2)application;

In my case I needed to pass this to a class looked like this:

public class MyClass

{

protected Microsoft.VisualStudio.OLE.Interop.IServiceProvider oleServiceProvider;

public MyClass(DTE dte)

{

this.oleServiceProvider = dte as Microsoft.VisualStudio.OLE.Interop.IServiceProvider;

}

}

And on the AddIn Exec method I had something like this:

MyClass myClass = new MyClass(_applicationObject);

As you can see this ended up being much simpler and cleaner than what I originally thought. One thing worth noting is that I had to fully qualify IServiceProvider because it was colliding with System.IServiceProvider.