views:

43

answers:

2

Consider the following interface:

public interface IMyCallback
{
  void SomeEvent(int someArg);
}

which is the contract for a WCF callback that will be receiving "events" from a WCF service. My implementation for this interface looks like this

public class MyCallback : IMyCallback
{
  void IMyCallback.SomeEvent(int someArg)
  {
    OnSomeEvent(someArg);
  }

  protected virtual void OnSomeEvent(int someArg)
  {
    EventHandler<SomeEventArgs> handler = this.SomeEvent;

    if (handler != null)
    {
      handler(this, new SomeEventArgs(someArg));
    }
  }

  public event EventHandler<SomeEventArgs> SomeEvent;
}

which allows me to instantiate the callback and hook the SomeEvent event in my client code. Whenever the server calls my callback, I receive it a plain old .NET event. Everything works great.

Here comes the question: I'd like to write a factory class to automate the creation of this callback so I easily re-use this approach in all my projects and with any interface. The factory would be called like this:

var myCallback = CallbackFactory.CreateCallback<IMyCallback>();

Can/should I use a mocking framework to dynamically create this class, or should I bite the bullet and emit IL directly? Or should I just hand code every implementation? Or is there another approach I'm not thinking of?

+1  A: 

You could use Castle Project's DynamicProxy which should give you all the infrastructure you need in order to generate a proxy. Then you don't have to worry about emitting IL which can have nasty side-effects if not done properly.

I don't know how you want to attach to the event in user code when using the proxy, simply because your IMyCallback does not have the actual event in it only the one called. Or did I misunderstand your question?

Tobias Hertkorn
A: 

I think that using a mocking framework is fine. In essence, a mocking/stub framework is nothing more than a way to easily provide implementations for type definitions for known inputs.

Since that's exactly what you are doing here, I say go with that.

casperOne