0

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

该服务的定义如MSDN“如何:注册服务”中所述。我省略了 ComVisibleAttribute,因为方法说明仅当服务需要在非托管代码中可用时才需要它,而事实并非如此。接口就像

[Guid("5A72348D-617B-4960-B07A-DC6CC5AA7675")]
public interface SMessageBus {}

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

提供服务的包遵循MSDN“如何:提供服务”。看起来像:

[<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
    ...
  }
}

这个另一个包被声明为

[<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“如何:服务疑难解答”中所述的所有要求都得到了满足。谁能告诉我我错过了什么?

4

1 回答 1

1

自己找到了答案...... Initialize() 的覆盖需要调用 base.Initialize() 因为这是注册服务实际上被提升到父服务容器。

于 2013-10-15T12:56:15.680 回答