-
Notifications
You must be signed in to change notification settings - Fork 0
/
MyDIContainer.cs
81 lines (68 loc) · 2.58 KB
/
MyDIContainer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
using System.Reflection;
using System.Runtime.CompilerServices;
public class MyDIContainer
{
private readonly Dictionary<Type, Type> _registeredTypes;
private readonly Dictionary<Type, object> _singletons = new();
public MyDIContainer()
{
_registeredTypes = new Dictionary<Type, Type>();
}
public void Register<TInterface, TImplementation>() where TImplementation : TInterface
{
_registeredTypes[typeof(TInterface)] = typeof(TImplementation);
}
public void RegisterSingleton<TInterface, TImplementation>() where TImplementation : TInterface
{
Register<TInterface, TImplementation>();
// add the type as singleton
_singletons[typeof(TInterface)] = null;
}
public TInterface Resolve<TInterface>()
{
return (TInterface)Resolve(typeof(TInterface));
}
public object Resolve(Type type)
{
if (_registeredTypes.ContainsKey(type))
{
// singleton check before instace
if (_singletons.TryGetValue(type, out var value) && value is not null)
return _singletons[type];
var implementationType = _registeredTypes[type];
var constructor = implementationType.GetConstructors().First();
var constructorParameters = constructor.GetParameters();
object? instace = null;
if (constructorParameters.Length == 0)
{
instace = Activator.CreateInstance(implementationType);
}
else
{
// if constructor has params
var parameterInstances = GetConstructorParameters(constructorParameters);
instace = Activator.CreateInstance(implementationType, parameterInstances.ToArray());
}
// add this instace to singleton dictionry
TryAddWhenSingleton(type, instace);
return instace;
}
throw new Exception($"The service {type.FullName} has not been registered!");
}
private List<Object> GetConstructorParameters(ParameterInfo[] constructorParameters)
{
var parameterInstances = new List<object>();
foreach (var parameter in constructorParameters)
{
var parameterType = parameter.ParameterType;
var parameterInstance = Resolve(parameterType);
parameterInstances.Add(parameterInstance);
}
return parameterInstances;
}
private void TryAddWhenSingleton(Type type, object instance)
{
if (_singletons.ContainsKey(type))
_singletons[type] = instance;
}
}