调整这个场地的命名空间,我已经用了很多年了......
using System;
using System.Collections.Generic;
using DataAccess.Core.DataInterfaces;
using DataAccess.Core.Utils;
namespace StackOverflowExample
{
public class SimpleIoC<T>
{
public T getInstance()
{
return getInstance(null);
}
public T getInstance(object[] initializationParameters)
{
Type type = Activator.CreateInstance(typeof(T), initializationParameters).GetType();
// Any special initialization for an object should be placed in a case statement
// using that object's type name
switch (type.ToString())
{
// Example
//case "DataAccess.Data.ApplicantDao":
// // - Do pre-instanciation initialization stuff here -
// return (T)Activator.CreateInstance(typeof(T), initializationParameters);
default:
return (T)Activator.CreateInstance(typeof(T), initializationParameters);
}
}
}
}
不确定这是否会帮助您,但我将其用作业务规则评估引擎的一部分...
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
namespace StackOverflowExample
{
public static class DynamicObjectFactory
{
private static readonly object _lock = new object();
public static object getInstance(string assemblyName, string className)
{
Monitor.Enter(_lock);
try
{
System.Reflection.Assembly asm = System.Reflection.Assembly.Load(assemblyName);
return asm.CreateInstance(className, false, System.Reflection.BindingFlags.CreateInstance, null, null, null, null);
}
finally
{
Monitor.Exit(_lock);
}
}
public static object getInstance(string assemblyName, string className, object[] constructorParameters)
{
Monitor.Enter(_lock);
try
{
System.Reflection.Assembly asm = System.Reflection.Assembly.Load(assemblyName);
return asm.CreateInstance(className, false, System.Reflection.BindingFlags.CreateInstance, null, constructorParameters, null, null);
}
finally
{
Monitor.Exit(_lock);
}
}
}
}