I'm trying to create what is essentially a plugin framework for a project. I'm trying to work out the pieces before full blown development and I've run into a problem. I am building a message processor. Where the message comes from determines how the message should be processed. As retrieving the message and sending the message will be the same no matter where the message comes from, I felt that a plugin framework would be a good way to implement this.
I built an interface that all Implementations could be built against.
public interface IInterfaceProcessor
{
String ProcessRequest(XmlDocument xdoc, String processType);
}
I created a implementation for the interface just to test it out.
public class IIPImplimentation : IInterfaceProcessor
{
public IIPResult ProcessRequest(XmlDocument xdoc, String requestType)
{
IIPResult result = new IIPResult();
Console.WriteLine("In interface {0}", requestType);
return result;
}
}
And then I created a test project to try to bind the implementation file at runtime and then use the interface.
using IIPInterfaces;
using System;
using System.IO;
using System.Reflection;
using System.Xml;
namespace LateBindingPrototype
{
class Program
{
static void Main(string[] args)
{
String filePath = "C:\\XMLConfig\\PrototypeIIP.dll";
// Try to load a copy of PrototypeIIP
Assembly a = null;
try
{ a = Assembly.LoadFrom(filePath); }
catch(FileNotFoundException e)
{
Console.WriteLine(e.Message);
Console.ReadKey();
return;
}
if (a != null)
{ CreateUsingLateBinding(a); }
Console.ReadKey();
InvokeProcessMessage(a);
Console.ReadKey();
}
static void InvokeProcessMessage(Assembly asm)
{
try
{
Type processor = asm.GetType("PrototypeIIP.IIPImplimentation");
IInterfaceProcessor myProcessor = Activator.CreateInstance(processor) as IInterfaceProcessor;
XmlDocument xdoc = new XmlDocument();
myProcessor.ProcessRequest(xdoc, "test");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.ReadKey();
}
}
static void CreateUsingLateBinding(Assembly asm)
{
try
{
Type processor = asm.GetType("PrototypeIIP.IIPImplimentation");
object obj = Activator.CreateInstance(processor);
Console.WriteLine("Created a {0} using late finding!", obj);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.ReadKey();
}
}
}
}
The CreateUsingLateBinding Method works fine but when I try to create in instance of IInterfaceProcessor in the InvokeProcessMessage method the object is null.
Is what I am trying to do possible? I know that I could do this by bypassing the interface and calling the methods directly from the implementation dll but I was hoping to keep the code cleaner than that because others in our development group will need to support this and simpler is better when it comes to some of them.
Thanks!
Aucun commentaire:
Enregistrer un commentaire