我是一名学生,我的工作是构建自己的 IoC 容器。我已经阅读了一些教程/代码示例并最终创建了它,但是当我尝试创建它的实例时,我得到了主题中的异常。这是我的 IoC 代码和测试代码,我一直在试图找出问题所在,但就是找不到。
国际奥委会
public class Mkontener: UnresolvedDependenciesException, IContainer
{
private readonly Dictionary<Type, object> container = new Dictionary<Type, object> { };
public void Register(System.Reflection.Assembly assembly)
{
Type[] mytypes = assembly.GetTypes();
foreach (Type t in mytypes)
{
if (!container.ContainsKey(t))
{
container.Add(t, Activator.CreateInstance(t));
}
}
//throw new NotImplementedException();
}
public void Register(Type type)
{
if (!container.ContainsKey(type))
{
container.Add(type, Activator.CreateInstance(type));
}
//throw new NotImplementedException();
}
public void Register(object impl)
{
Type t = impl.GetType();
if (!container.ContainsKey(t))
{
container.Add(t, impl);
}
// throw new NotImplementedException();
}
public void Register<T>(Func<T> provider) where T : class
{
container.Add(provider.GetType(), provider);
//throw new NotImplementedException();
}
public T Resolve<T>() where T : class
{
return (T)Resolve(typeof(T));
}
public object Resolve(Type type)
{
List<ConstructorInfo> konstruktor = new List<ConstructorInfo> { };
foreach (ConstructorInfo cons in type.GetConstructors())
{
konstruktor.Add(cons);
}
if (konstruktor.Count == 0)
{
return Activator.CreateInstance(type);
}
else
{
ConstructorInfo active = null;
int lparams = 0;
foreach (ConstructorInfo cnst in konstruktor)
{
int inner=0;
foreach (ParameterInfo a in cnst.GetParameters())
{
inner++;
}
if (inner > lparams)
{
active = cnst;
}
}
List<object> lista = new List<object> { };
foreach(ParameterInfo param in active.GetParameters())
{
if (container.ContainsKey(param.GetType()))
{
lista.Add(container[param.GetType()]);
}
else
{
//throw new UnresolvedDependenciesException();
}
}
object[] obiekty= lista.ToArray();
return Activator.CreateInstance(type, obiekty);
}
if (container.ContainsKey(type))
{
return container[type];
}
else
{
//throw new UnresolvedDependenciesException();
}
}
public void Register<T>(T impl) where T : class
{
container.Add(impl.GetType(), impl);
}
}
部分测试单元
public void P1__Container_Should_Register_Singleton_As_Object()
{
// Arrange
var container = (IContainer)Activator.CreateInstance(LabDescriptor.Container);
var singleton = new FakeImpl();
// Act
container.Register(singleton);
var result = container.Resolve<IFake>();
// Assert
Assert.That(result, Is.Not.Null);
Assert.That(result, Is.SameAs(singleton));
}
对不起,笨拙的代码等。刚从这里开始。