Reputation: 1281
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?
Upvotes: 4
Views: 232
Reputation: 39277
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.
Upvotes: 2
Reputation: 65496
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)
Upvotes: 1