m3th0dman showed the general principle, but his solution doesn't quite fit the problem as I understand it, since your method names make me think that CallMeDuringAPplicationLifecycle
can be called multiple times.
In C#, a resource that needs cleanup (such as flushing buffers or closing connections) should use implement IDisposable
.
interface IConnectionFactory
{
IConnection connect(); // This is CallMeFirst
}
interface IConnection : IDisposable
{
void send(); // This is CallMeDuringApplicationLifecycle
}
// And the Dispose() method of IDisposable is CallMeOnApplicationExit.
This way, you enforce that CallMeFirst
is called first, because there's no other way to obtain an IConnection
. And because C# programmers recognize IDisposable
, they know that they have to call Dispose
when they're done with the connection. You cannot actually enforce this in C#, so this is as close as you can get. (You can also write a finalizer that checks that Dispose
was called, but you can't do anything but log the mistake there, and there's no guarantee that finalizers will be called.)