public interface IContainer
{
void Register<TTypeToResolve, TConcrete>();
void Register<TTypeToResolve, TConcrete>(LifeCycle lifeCycle);
TTypeToResolve Resolve<TTypeToResolve>();
object Resolve(Type typeToResolve);
}
public enum LifeCycle
{
Singleton,
Transient
}
public class RegisteredObject
{
public RegisteredObject(Type typeToResolve, Type concreteType, LifeCycle lifeCycle)
{
TypeToResolve = typeToResolve;
ConcreteType = concreteType;
LifeCycle = lifeCycle;
}
public Type TypeToResolve { get; private set; }
public Type ConcreteType { get; private set; }
public object Instance { get; private set; }
public LifeCycle LifeCycle { get; private set; }
public void CreateInstance(params object[] args)
{
this.Instance = Activator.CreateInstance(this.ConcreteType, args);
}
}
public class SimpleIocContainer : IContainer
{
private readonly IList<RegisteredObject> registeredObjects = new List<RegisteredObject>();
public void Register<TTypeToResolve, TConcrete>()
{
Register<TTypeToResolve, TConcrete>(LifeCycle.Singleton);
}
public void Register<TTypeToResolve, TConcrete>(LifeCycle lifeCycle)
{
registeredObjects.Add(new RegisteredObject(typeof (TTypeToResolve), typeof (TConcrete), lifeCycle));
}
public TTypeToResolve Resolve<TTypeToResolve>()
{
return (TTypeToResolve) ResolveObject(typeof (TTypeToResolve));
}
public object Resolve(Type typeToResolve)
{
return ResolveObject(typeToResolve);
}
private object ResolveObject(Type typeToResolve)
{
var registeredObject = registeredObjects.FirstOrDefault(o => o.TypeToResolve == typeToResolve);
if (registeredObject == null)
{
throw new TypeNotRegisteredException(string.Format(
"The type {0} has not been registered", typeToResolve.Name));
}
return GetInstance(registeredObject);
}
private object GetInstance(RegisteredObject registeredObject)
{
if (registeredObject.Instance == null ||
registeredObject.LifeCycle == LifeCycle.Transient)
{
var parameters = ResolveConstructorParameters(registeredObject);
registeredObject.CreateInstance(parameters.ToArray());
}
return registeredObject.Instance;
}
private IEnumerable<object> ResolveConstructorParameters(RegisteredObject registeredObject)
{
var constructorInfo = registeredObject.ConcreteType.GetConstructors().First();
foreach (var parameter in constructorInfo.GetParameters())
{
yield return ResolveObject(parameter.ParameterType);
}
}
}
public class TypeNotRegisteredException : Exception
{
public TypeNotRegisteredException(string message)
: base(message)
{
}
}
16 October 2017
Basic Dependency Injection control
I found a simple Inversion Controller on
https://timross.wordpress.com/2010/01/21/creating-a-simple-ioc-container
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment