forked from tigernetframework/Tigernet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTigernetHostBuilder.DI.cs
61 lines (53 loc) · 1.86 KB
/
TigernetHostBuilder.DI.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
namespace Tigernet.Hosting
{
public partial class TigernetHostBuilder
{
/// <summary>
/// DI Container
/// </summary>
private readonly Dictionary<Type, Type> _services;
/// <summary>
/// Adds interface and implementation of it to DI
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="TImpl"></typeparam>
public void AddService<T, TImpl>() where TImpl : T
{
_services[typeof(T)] = typeof(TImpl);
}
/// <summary>
/// Get added service
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public T Get<T>()
{
return (T)GetService(typeof(T));
}
/// <summary>
/// Gets added service and constructs it returning as object
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
/// <exception cref="InvalidOperationException"></exception>
private object GetService(Type type)
{
if (_services.TryGetValue(type, out var implementationType))
{
var constructor = implementationType.GetConstructors()[0];
var parameters = constructor.GetParameters();
if (parameters.Length == 0)
{
return Activator.CreateInstance(implementationType);
}
var parameterInstances = new object[parameters.Length];
for (var i = 0; i < parameters.Length; i++)
{
parameterInstances[i] = GetService(parameters[i].ParameterType);
}
return constructor.Invoke(parameterInstances);
}
throw new InvalidOperationException($"Type {type} not registered");
}
}
}