5

I'm working on something that needs to take in a contract (specified as an interface), and create a instance on the fly, without any formally defined concrete class that meets this interface.

An example of the syntax is like this:

IExampleMessage message = MessageBuilder.Create<IExampleMessage>(x => {
   x.PropertyA = "Test";
   x.PropertyB = 5;
});

I've seen other .NET libraries and frameworks offer behavior like this (NServiceBus comes to mind), and I'm wondering if there is a 3rd party library that abstracts the runtime code gen away. I thought Castle DynamicProxy would be a place to look, but this seems focused entirely on proxying and intercepting, and does not seem to expose the code generation aspect.

I could write up a implementation that uses Reflection.Emit to create the class on the fly, however I'd rather use a solid open source library if one exists.

Any suggestions?

3
  • I saw similar code in BLTookit
    – adontz
    Aug 21, 2011 at 23:45
  • I'm curious: How would interfaces with methods be supported? How do you intend to specify a custom implementation of a method with that syntax?
    – Peter O.
    Aug 21, 2011 at 23:59
  • Interfaces with methods are not supported Aug 22, 2011 at 0:15

2 Answers 2

2

Impromptu interface is what you need:- http://code.google.com/p/impromptu-interface/

I've used it to create polymorphic types in .NET.

You could also look at Clay.

2
  • I was trying to stay away from Dynamic. However that stuff is pretty cool. Aug 22, 2011 at 1:32
  • 1
    @Jonathan-Holland in the use-case you are describing wouldn't require you to actually see any usage of dynamic in your code when using impromptu (though it will be happening behind the scenes). Example implementation: public T Create<T>(Action<T> init) where T:class {var message= new ExpandoObject().ActLike<T>(); init(message); return message;}
    – jbtule
    Aug 29, 2011 at 18:13
1

What about the mocking libraries - NMock, and RhinoMocks?

You can add implementations to the concrete types using stubs/expectations as well.

Rhino in particular has a nice lambda based syntax for the kind of thing that you want.

Does this not full fill your needs?

Something like this?

IExampleMessage message = MockRepository.GenerateStub<IExampleMessage>();
message .Stub(x => x.PropertyA).Return("Text")    
message .Stub(x => x.PropertyB).Return(5)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.