Lets focus on ProjectAdded
event (although described issue is exactly the same for the rest of the events).
The code sample you've shown attempts to register the SolutionEvents_ProjectAdded
handler for the ProjectAdded
event. However, the SolutionEvents
object exposing the event, has lifetime scope limited to the closure of its wrapping method (you haven't shown its signature - let's call it Connect
). After the control flow had left that scope, local object has already been garbage collected, so its event is never called:
Broken code:
public class Connector
{
public void Connect()
{
((Events2)dte.Events).SolutionEvents.ProjectAdded += SolutionEvents_ProjectAdded;
}
void SolutionEvents_ProjectAdded()
{
// callback is dead
}
}
To fix that, you need to assign the SolutionEvents
object to some variable, whose lifetime spans over the SolutionEvents_ProjectAdded
handler - e.g. over the entire wrapping class. In the example below, the scope extends over the entire type (let's call it Connector
), and ensures that the handler is accessible during the lifetime of that type:
Fixed code:
public class Connector
{
SolutionEvents _solutionEvents;
public void Connect()
{
_solutionEvents = ((Events2)dte.Events).SolutionEvents;
_solutionEvents.ProjectAdded += SolutionEvents_ProjectAdded;
}
void SolutionEvents_ProjectAdded()
{
// callback works
}
}
To be more precise, check this MSDN reference - Scoping Variables Appropriately in Event Handlers:
A common mistake in programming event handlers is connecting the event
handler to an object that has been declared with a scope too limited
for the purpose of handling the event. The object must have a life
that spans not just over the function that connects the callback
method as an event handler of the object, but also over the callback
method itself where the event is actually handled. Otherwise, if the
object is out of scope and is no longer defined in the callback
method, the callback method is not called and the event is not handled
as desired.
_hSolutionEvents
inInitialize()
? – Koon