DI Container 是指用來提供Dependency Injection(相依性注入)的容器,容器內的結構基本上都是各種Class 的Constructor,並且在需要提供注入的地方建立Object , Ex:
public class DIContainer
{
private List<Type> objectFactory = new List<Type>();
public void Register(Type type)
=> objectFactory.Add(type);
public object Resolve(Type type)
=> objectFactory.ContainKey(type) ? CreateObject(type) : throw;
private object CreateObject(Type type)
=> Activator.CreateInstance(type);
}
var di = new DIContainer();
di.Register(typeof(Foo));
Foo foo = di.Resolve(typeof(Foo));
Bar bar = di.Resolve(typeof(Bar)); // throw error