[英]How do you instantiate an object that is not included in your C# project?
Note: All sample code is greatly simplified. 注意:所有示例代码都大大简化了。
I have a DLL defined as: 我有一个DLL定义为:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;
namespace RIV.Module
{
public interface IModule
{
StringWriter ProcessRequest(HttpContext context);
string Decrypt(string interactive);
string ExecutePlayerAction(object ParamObjectFromFlash);
void LogEvent(object LoggingObjectFromFlash);
}
}
Now, outside of my solution, other developers can define concrete classes and drop them into the BIN folder of my app. 现在,在我的解决方案之外,其他开发人员可以定义具体的类并将它们放入我的应用程序的BIN文件夹中。 Maybe something like: 也许是这样的:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RIV.Module;
namespace RIV.Module.Greeting
{
public class Module : IModule
{
public System.IO.StringWriter ProcessRequest(System.Web.HttpContext context)
{
//...
}
public string Decrypt(string interactive)
{
//...
}
public string ExecutePlayerAction(object ParamObjectFromFlash)
{
//...
}
public void LogEvent(object LoggingObjectFromFlash)
{
//...
}
}
}
Now, in my app I would need to know that a new Module was available (I am guessing via web.config or something along those lines) and then be able to call it based off of some trigger in the database Campaign table (which maps to the module to use for that specific campaign). 现在,在我的应用程序中,我需要知道一个新的模块可用(我猜通过web.config或其他类似的东西),然后能够根据数据库Campaign表中的一些触发器调用它(这些映射到用于该特定活动的模块)。
I am trying to instantiate it this way: 我试图以这种方式实例化它:
var type = typeof(RIV.Module.Greeting.Module);
var obj = (RIV.Module.Greeting.Module)Activator.CreateInstance(type);
However, the compiler belches because a reference was never set to RIV.Module.Greeting.dll ! 但是,编译器打气,因为从未将引用设置为RIV.Module.Greeting.dll !
What am I doing wrong? 我究竟做错了什么?
You need to use more reflection: 你需要使用更多的反射:
Assembly.Load
通过调用Assembly.Load
加载程序集 someAssembly.GetType(name)
or searching someAssembly.GetTypes()
通过调用someAssembly.GetType(name)
或搜索someAssembly.GetTypes()
查找类型 Type
instance to Activator.CreateInstance
将Type
实例传递给Activator.CreateInstance
Instead of typeof(RIV.Module.Greeting.Module), try using 而不是typeof(RIV.Module.Greeting.Module),尝试使用
var type = Type.GetType("RIV.Module.Greeting.Module, RIV.Module.Greeting");
(ie load the type by specifying its assembly-qualified name as string) and casting to IModule. (即通过将其程序集限定的名称指定为字符串来加载类型)并转换为IModule。
This approach requires you to know the exact class and assembly names of the modules (as you wrote, they could be stored in web.config). 这种方法要求您知道模块的确切类和程序集名称(如您所写,它们可以存储在web.config中)。
Alternatively, you could go for a completely dynamic plugin approach: 或者,您可以采用完全动态的插件方法:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.