After reflecting upon all the great answers I received to my previous question about modeling my code to maximize code re-use, I started wondering if it would be possible to assign the interface to an object at runtime instead of when it is coded.
Take, for example, a simplified portion of code from my previous question:
public class OutboxManager
{
private IVendorMessenger _VendorMessenger;
//This is the default constructor, forcing the consumer to provide
//the implementation of IVendorMessenger.
public OutboxManager(IVendorMessenger messenger)
{
_VendorMessenger = messenger;
}
public void DistributeOutboxMessages()
{
VendorMessenger.SendMessageToVendor()
_OutboxMgrDataProvider.MarkMessageAsProcessed(om)
}
}
Currently, if someone wants to consume this class, they have to code a class that implements IVendorMessenger
and provide it during initialization as a parameter:
var MyOutboxManger = new OutboxManager(new MyVendorMessenger())
What if, instead of hard-coding the interface parameter, it instead gets assinged at runtime? This way, I could compile a dll for a class that implements IVendorMessenger
, drop it into the same folder that OutboxManagerExecutable
exists, and it will wire everything up at run time. I suppose, using this logic, I could figure out a way to drop multiple implementations of IVendorMessenger
in the same folder and design the executable to be smart enough to iterate through all appropriate dlls and consume them accordingly.
Is this type of functionality possible in .NET 4?
Check out the Managed Extensibility Framework (MEF). It can automatically compose the dependencies of your application just as you describe. It shipped with .NET 4.0.
This is a pretty common use case for reflection. The .NET API gives you the pieces you need to:
Directory.GetFiles()
Assembly.LoadFile()
Assembly.GetTypes()
Type.IsAssignableFrom()
Type.GetConstructor()
After that, you've got an Object
that you can cast to IVendorMessenger
and pass it in.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With