【发布时间】:2010-12-21 17:39:44
【问题描述】:
我正在尝试提出一个方法工厂,该方法工厂在 config 内部查找以获取要实例化的类型的全名并动态创建该对象类型。
这是我的类型和接口:
public interface IComponent<T>
{
IEnumerable<T> DataSource {get; set;}
void PerformTask(object executionContext);
}
namespace MyCompany.Components
{
public class ConcreteComponent1<T> : IComponent<T>
{
private IEnumerable<Contact> contactSource = null;
internal ConcreteComponent1() {}
public void PerformTask(object executionContext)
{
this.contactSource = GetSource(executionContext);
foreach(var result in this.contactSource)
{
result.Execute(executionContext);
}
}
public IEnumerable<T> DataSource
{
get { return this.contactSource as IEnumerable<T>; }
set { this.contactSource = (IContactSource)value; }
}
}
}
工厂,驻留在同一个程序集中:
//Factory - Same assembly
public static class ComponentFactory<T>
{
public static IComponent<T> CreateComponent()
{
var assembly = Assembly.GetExecutingAssembly();
object o = assembly.CreateInstance("MyCompany.Components.ConcreteComponent1"); //o is null...
var objectHandle = Activator.CreateInstance(Assembly.GetAssembl(typeof(ComponentFactory<T>)).GetName().FullName, "MyCompany.Components.ConcreteComponent1"); //throws Could not load type from assembly exception.
return o as IComponent<T>;
}
}
所以在第一种情况下,o 始终为空。
在第二种情况下,当使用 Activator 类时,它会抛出 Type could not be loaded from assembly "MyAssembly"。没有内在的例外。我做错了什么?
【问题讨论】:
标签: c# .net .net-3.5 dynamic factory