首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用VSPackage A在VSPackage B中提供的服务?

如何使用VSPackage A在VSPackage B中提供的服务?
EN

Stack Overflow用户
提问于 2013-10-15 12:29:39
回答 1查看 313关注 0票数 0

我有两个VSPackages。第一个提供全球服务。两个VSPackages都使用该服务。

该服务被定义为在MSDN“如何:注册服务”中解释。我省略了ComVisibleAttribute,因为“如何- to”说,只有当服务需要在非托管代码中可用时才需要它,而它不是这样。

代码语言:javascript
复制
[Guid("5A72348D-617B-4960-B07A-DC6CC5AA7675")]
public interface SMessageBus {}

[Guid("04A499BA-CE09-48AF-96D5-F32DEAF0754C")]
public interface IMessageBus { ... }

服务提供包遵循MSDN“如何:提供服务”。看上去:

代码语言:javascript
复制
[<package atttributes>]
[ProvideService(typeof(SMessageBus))]
public sealed class MessageBusProviderPackage : Package
{
  public MessageBusProviderPackage()
  {
    var serviceContainer = this as IServiceContainer;
    var serviceCreatorCallback = new ServiceCreatorCallback(CreateMessageBusService);
    serviceContainer.AddService(typeof(SMessageBus), serviceCreatorCallback, true);
  }

  private object CreateMessageBusService(IServiceContainer container, Type serviceType)
  {
    // this gets called and returns a new bus instance
    return (serviceType == typeof(SMessageBus)) ? new MyMessageBus() : null;
  }

  protected override void Initialize()
  {
    // this is called after the package was constructed
    // the call leads to the service being created by CreateMessageService()
    var messageBus = GetService(typeof(SMessageBus)) as IMessageBus;
    // the bus is retrieved correctly
    ...
  }
}

另一个包声明如下

代码语言:javascript
复制
[<package attributes>]
[ProvideAutoLoad(VSConstants.UICONTEXT.NoSolution_string)]
public sealed class MessageGeneratorPackage : Package
{
  protected override void Initialize()
  {
    // the call below is reached first, in its course the provider is loaded
    var service = GetService(type(SMessageBus));
    // this point is reached last, but service is null
    ...
  }
}

我在启动阶段进行了调试,发现MessageGeneratorPackage首先被创建和初始化。这意味着包裹已经放置好了。当到达Initialize()中的GetService()调用时,VS加载我的服务提供者,也就是说,ProvideServiceAttribute正确地将MessageBusProviderPackage标记为SMessageBus服务的提供者。提供者包被实例化,它的Initialize()方法被调用,其中成功地检索了服务。然后,消费者包的初始化继续进行,但是服务请求返回null。在我看来,MSDN“如何:故障排除服务”中所述的所有要求都得到了满足。有人能告诉我我错过了什么吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-10-15 12:56:15

我自己找到了答案。初始化()的重写需要调用base.Initialize(),因为已经注册的服务实际上被提升到父服务容器。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19381283

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档