75 lines
3.2 KiB
C#
75 lines
3.2 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>
|
|
/// <param name="instance">instance of the service</param>
|
|
public void RegisterType<TService, TInterface>(bool isSingleton, TService instance = default(TService)) where TService : TInterface
|
|
{
|
|
_container.Add(typeof(TInterface), new RegisteredType(typeof(TService), isSingleton, null));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Register types in the resolve container.
|
|
/// </summary>
|
|
/// <typeparam name="TService">Type of the service.</typeparam>
|
|
public void RegisterType<TService>(bool isSingleton, TService instance = default(TService)) => RegisterType<TService, TService>(isSingleton, instance);
|
|
|
|
/// <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.Instance != null)
|
|
return registeredType.Instance;
|
|
var constructor = registeredType.ServiceType.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);
|
|
}
|
|
var instance = constructor.Invoke(constructorParameters);
|
|
return registeredType.IsSingleton ? (registeredType.Instance = instance) : instance;
|
|
}
|
|
|
|
private class RegisteredType
|
|
{
|
|
public RegisteredType(Type serviceType, bool isSingleton, object instance)
|
|
{
|
|
ServiceType = serviceType;
|
|
IsSingleton = isSingleton;
|
|
Instance = instance;
|
|
}
|
|
|
|
public readonly bool IsSingleton;
|
|
public readonly Type ServiceType;
|
|
public object Instance { get; set; }
|
|
}
|
|
}
|
|
} |