了解 Component.GetService()
我在用户控件中有一个带有此代码的方法
public bool GetActiveDocument(ref EnvDTE.Document doc)
{
try
{
var dte = (DTE2)GetService(typeof(SDTE));
doc = dte.ActiveDocument;
if (doc == null)
{
MessageBox.Show("There isn't any file open in the Code Editor");
return false;
}
else return true;
}
catch (Exception)
{
MessageBox.Show("There was a problem getting the actual file, verify if it is open");
return false;
}
}
,我想将此方法移动到“代理”类,该类将充当 Visual Studio 和我的应用程序之间的中介。问题是 GetService 仅在控件内部调用时才能正确返回活动文档。当我将该方法移至 Proxy 类时,GetService 没有定义。我搜索到这个方法来自ComponentModel.Component,所以我让Proxy类从Component派生。一切都编译正常,但当我请求活动文档时总是会发生异常。我认为我不太了解 GetService() 方法的工作原理。请帮忙解决这个问题。
i have a method in a Usercontrol with this code
public bool GetActiveDocument(ref EnvDTE.Document doc)
{
try
{
var dte = (DTE2)GetService(typeof(SDTE));
doc = dte.ActiveDocument;
if (doc == null)
{
MessageBox.Show("There isn't any file open in the Code Editor");
return false;
}
else return true;
}
catch (Exception)
{
MessageBox.Show("There was a problem getting the actual file, verify if it is open");
return false;
}
}
I want to move this method to a "Proxy" class that is going to act as an intermediary between Visual Studio and my application. The problem is that GetService only return the active document correctly if it is call inside the control. When i move that method to the Proxy class, GetService doesn't have definition. I search that this method comes from ComponentModel.Component, so i made the Proxy class derive from Component. Everything compiles OK but always when i ask for the active document an exception occurs. I thing that i'm not understanding well how works the GetService() method. Please help with this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Component.GetService 在分配给组件的 Site 属性(假设有一个)的 ISite 实例上调用 IServiceProvider.GetService。您不需要让代理实例继承自 Component,但您需要授予它对 ISite/IServiceProvider 的访问权限。
Component.GetService invokes IServiceProvider.GetService on the ISite instance assigned to the component's Site property (assuming there is one). You shouldn't need to make your proxy instance inherit from Component, but you will need to give it access to the ISite/IServiceProvider.