Remember – Services are singletons

Within the past week, services have been a big issue on two fronts. First, it was found that some services VS provides would create a new instance every time you called it. Second, in my last post I described a bug where input in one buffer would appear in another one. Remember, services in VS should be singletons – meaning that every time a QueryService call is made, you should return the same object as any previous calls to QueryService. This was a bug in some of our services in VS where every time you would call QueryService(SomeServiceGuid, SomeInterfaceGuid) you would get back a new, distinct object from the first invocation.


It was also a bug in my IL language service. I started the code by just heaping all the interfaces I would need for a language service onto my service object. This service object would be created once when the package would load, and because most of my testing would involve only one document open at a time, it worked fine. But when I started to do real work with IL, it would fail. Since the service was created only once, this means that only one instance of my command filter was being created, one instance of IVsTextLines was being tracked, etc. After splitting the document specific code from the service, everything is now working fine.


So remember – if you are authoring a service object, that object should only be created once. If there are more instances of that service being created, it is a bug. If you get a service and then get that same service again but the two objects are not the same (the pointer to the objects do not match), it is a bug,

Comments (0)

Skip to main content