【发布时间】:2015-02-04 00:52:04
【问题描述】:
我正在尝试为项目创建本质上是插件框架的东西。我正在尝试在全面开发之前解决这些问题,但我遇到了问题。我正在构建一个消息处理器。消息的来源决定了应该如何处理消息。因为无论消息来自哪里,获取消息和发送消息都是一样的,所以我觉得插件框架是实现这一点的好方法。
我构建了一个可以构建所有实现的接口。
IIPInterfaces.cs:
using System;
using System.Xml;
namespace IIPInterfaces
{
public interface IInterfaceProcessor
{
IIPResult ProcessRequest(XmlDocument xdoc, String processType);
}
public class IIPResult
{
public XmlDocument ResponseDocument { get; set;}
Boolean IsSuccessful { get; set; }
String Error { get; set; }
}
}
我为接口创建了一个实现,只是为了测试它。
原型IIP
using IIPInterfaces;
using System;
using System.Xml;
namespace PrototypeIIP
{
public class IIPImplimentation : IInterfaceProcessor
{
public IIPResult ProcessRequest(XmlDocument xdoc, String requestType)
{
IIPResult result = new IIPResult();
Console.WriteLine("In interface {0}", requestType);
return result;
}
}
}
然后我创建了一个测试项目,尝试在运行时绑定实现文件,然后使用接口。
控制台程序
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();
}
}
}
}
CreateUsingLateBinding 方法工作正常,但是当我尝试在 InvokeProcessMessage 方法中的 IInterfaceProcessor 实例中创建对象时,该对象为空。
我正在尝试做的事情可能吗?我知道我可以通过绕过接口并直接从实现 dll 调用方法来做到这一点,但我希望保持代码比这更干净,因为我们开发组中的其他人将需要支持这一点,并且在涉及到时越简单越好其中一些。
谢谢!
【问题讨论】:
-
基本上你想要 IoC(控制反转)。看看 Unity (msdn.microsoft.com/en-us/library/ff647202.aspx) 或 MEF (msdn.microsoft.com/en-us/magazine/ee291628.aspx)。
-
我认为您在这里尝试的内容没有明显错误。但是,我目前没有运行 VS,所以希望其他人会介入并查明您的错误。
-
您在哪里定义了接口,您是否使用相同的参考程序集在实现 dll 和运行您的示例代码的程序中定义接口文件。 (如果你有A.dll和B.exe是
IInterfaceProcessor在A和B中定义,只是B,或者A和B都有引用的C.dll) -
运行您的代码并从这两种方法创建实例都没有问题,我看到的唯一问题是
ProcessRequest的返回类型在您的界面中是string,但IIPResult在您的实施中。 -
Prestion - 两者都是 IIPResult。字符串来自于思考一件事并输入另一件事。
标签: c# reflection interface