views:

43

answers:

2

I've seen examples of this where an interface is provided to a factory and it generates objects that implement the interface. This isn't that complicated to me, but what I don't get is how that can be used to implement behavior.

Take for example the ChannelFactory in WCF... when you generate a channel from an interface it exposes methods (from the interface) that when invoked call remote procedures. I seem to have a small gap in my knowledge on how this can be done. It's probably a common design pattern but I figured I'd use SO as a research extension once again.

+1  A: 

Mocking frameworks that mock an interface generate a dynamic class that implements the interface. The behavior of the mocked method(s) will depend on the framework. Generally, the method will do nothing unless an implementation is provided through the mock.

For example:

Mock<IRepository> repMock = new Mock<IRepository>();
repMock.Setup(r => r.FindById(1)).Returns(new MyObject());

Assuming the IRepository interface defines a FindByID method, the Setup method of the mock dynamically generates an implementation of the method and "injects" it into the mock. This is done using Reflection.Emit, which can be used to dynamically build IL instructions and compile them on the fly.

Dave Swersky
Wouldn't repMock be simply of type IRepository? An object strongly typed as `Mock<IRepository>` wouldn't be seen as an IRepository itself. Beyond that, yeah, the framework will usually use reflection to dynamically generate some variation of a MockBase class that implements the desired interface, and the methods exposed by the interface are implemented using callbacks to centralized MockBase members that control expected behavior.
KeithS
@Keith: repMock is of type Moq.Mock. The repMock.Object is a dynamically-generated class that implements IRepository. The Setup injects an implementation into the class for whatever method(s) are defined by the interface.
Dave Swersky
OK, I'm used to RhinoMocks, where you use static GenerateMock methods to produce a class that looks like an IRepository. Moq apparently is a little different.
KeithS
+1  A: 

Usually happens through code emission. See the classes in System.Reflection.Emit.

For example, you could get an interface Type and go over the methods it declares, then build your own type which inherits it, using TypeBuilder, and implement whatever functionality you desire in the methods (or just them make empty / do a return default(T)), using MethodBuilder, and so on, until you've satisfied the interface.

Zor