79 lines
3.1 KiB
C#
79 lines
3.1 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
|
|
namespace SmallInjectorDemo
|
|
{
|
|
/// <summary>
|
|
/// A small dependency injector to demonstrate the pattern.
|
|
/// </summary>
|
|
public class SmallInjector
|
|
{
|
|
private readonly Dictionary<Type, RegisteredType> _container = new Dictionary<Type, RegisteredType>();
|
|
|
|
/// <summary>
|
|
/// Register types in the resolve container.
|
|
/// </summary>
|
|
/// <typeparam name="TService">Type of the service.</typeparam>
|
|
/// <typeparam name="TInterface">Type of the interface of the service.</typeparam>
|
|
/// <param name="isSingleton">True if the service should be singleton. False otherwise.</param>
|
|
public void RegisterType<TService, TInterface>(bool isSingleton)
|
|
{
|
|
_container.Add(typeof(TInterface), new RegisteredType(typeof(TService), isSingleton));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Register types in the resolve container.
|
|
/// </summary>
|
|
/// <typeparam name="TService">Type of the service.</typeparam>
|
|
public void RegisterType<TService>(bool isSingleton) => RegisterType<TService, TService>(isSingleton);
|
|
|
|
/// <summary>
|
|
/// Resolve service of specified type.
|
|
/// </summary>
|
|
/// <typeparam name="TService">Type of the service.</typeparam>
|
|
/// <returns>A instance of the service.</returns>
|
|
public TService Resolve<TService>() => (TService)Resolve(typeof(TService));
|
|
|
|
/// <summary>
|
|
/// Resolve service of specified type.
|
|
/// </summary>
|
|
/// <param name="serviceInterface">Type of the service.</param>
|
|
/// <returns>A instance of the service.</returns>
|
|
public object Resolve(Type serviceInterface)
|
|
{
|
|
if (!_container.TryGetValue(serviceInterface, out var registeredType))
|
|
{
|
|
throw new Exception("Can't resolve dependency " + serviceInterface);
|
|
}
|
|
|
|
if (registeredType.IsSingleton && registeredType.SingletonInstance != null)
|
|
return registeredType.SingletonInstance;
|
|
var constructor = registeredType.ConcreteType.GetConstructors()[0];
|
|
var parameters = constructor.GetParameters();
|
|
var constructorParameters = new object[parameters.Length];
|
|
for (var i = 0; i < parameters.Length; i++)
|
|
{
|
|
constructorParameters[i] = Resolve(parameters[i].ParameterType);
|
|
}
|
|
|
|
if (registeredType.IsSingleton)
|
|
{
|
|
return registeredType.SingletonInstance ?? (registeredType.SingletonInstance = constructor.Invoke(constructorParameters));
|
|
}
|
|
return constructor.Invoke(constructorParameters);
|
|
}
|
|
|
|
private class RegisteredType
|
|
{
|
|
public RegisteredType(Type concreteType, bool isSingleton)
|
|
{
|
|
ConcreteType = concreteType;
|
|
IsSingleton = isSingleton;
|
|
}
|
|
|
|
public readonly bool IsSingleton;
|
|
public readonly Type ConcreteType;
|
|
public object SingletonInstance { get; set; }
|
|
}
|
|
}
|
|
} |