COM+ Loosely Coupled Events

.NET provides managed classes with an easy way to hook up a server that fires events with client sinks. The .NET mechanism is certainly an improvement over the somewhat cumbersome COM connection point protocol, but the .NET mechanism still suffers from all the disadvantages of tightly coupled events, as explained at the beginning of Chapter 9. Fortunately, managed classes can easily take advantage of COM+ loosely coupled events.

The EventClass attribute is used to mark a serviced component as a COM+ event class, as shown in Example 10-17.

Example 10-17. Designating a serviced component as an event class using the EventClass attribute

public interface IMySink
{   
   void OnEvent1(  );   
   void OnEvent2(  );
}

[EventClass]
public class MyEventClass : ServicedComponent,IMySink
{
   public void OnEvent1(  )
   {
      throw(new NotImplementedException(exception));
   }
   public void OnEvent2(  )
   {
      throw(new NotImplementedException(exception));
   }
   const string exception = @"You should not call an event class directly. 
                            Register this assembly using RegSvcs /reconfig";
}

The event class implements a set of sink interfaces you want to publish events on. Note that it is pointless to have any implementation of the sink interface methods in the event class, as the event class’s code is never used. It is used only as a template, so that COM+ could synthesize an implementation, as explained in Chapter 9 (compare Example 10-17 with Example 9-1). This is why the code in Example 10-17 throws an exception ...

Get COM & .NET Component Services now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.