-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
135 lines (108 loc) · 3.04 KB
/
Program.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
using System;
using System.Collections.Generic;
namespace DI_and_IOC_demo
{
class Program
{
static void Main(string[] args)
{
WithoutDI withoutDi = new WithoutDI();
withoutDi.UseRepo();
Console.WriteLine();
Console.WriteLine("Next is our second class wich can work with different repositories.");
Console.WriteLine();
WithDI withDbDi = new WithDI(new DbRepository());
WithDI withFileDi = new WithDI(new FileRepository());
withDbDi.UseRepo();
withFileDi.UseRepo();
Console.WriteLine();
Console.WriteLine("IOC demo");
IOC ioc = new IOC();
ioc.Register("someRepo", new DbRepository());
ioc.Register("OtherRepo", new FileRepository());
Console.ReadLine();
}
}
/// <summary>
/// Class without Dependency Injection
/// </summary>
class WithoutDI
{
DbRepository _repository = new DbRepository();
public void UseRepo()
{
// Dummy logic.
Console.WriteLine("I am " + this.GetType().Name + " and I work with " + _repository.GetType().Name);
}
}
/// <summary>
/// Class with Dependency Injection
/// </summary>
class WithDI
{
private IRepository _repository;
public WithDI(IRepository repository)
{
_repository = repository;
}
public void UseRepo()
{
// Dummy logic.
Console.WriteLine("I am " + this.GetType().Name + " and I work with " + _repository.GetType().Name);
}
}
/// <summary>
/// Class with Dependency Injection
/// </summary>
class WithIOC
{
private IRepository _repository;
public WithIOC(IOC ioc)
{
_repository = (IRepository)ioc.Resolve("someRepo");
}
public void UseRepo()
{
// Dummy logic.
Console.WriteLine("I am " + this.GetType().Name + " and I work with " + _repository.GetType().Name + "recieved from IOC");
}
}
/// <summary>
/// My as simple as possible IOC
/// </summary>
class IOC
{
Dictionary<string, object> dependencies = new Dictionary<string, object>();
public void Register(string name, object obj)
{
dependencies.Add(name, obj);
}
public object Resolve(string name)
{
return dependencies[name];
}
}
#region Repository
internal interface IRepository
{
void Create();
void Read();
void Update();
void Delete();
}
class DbRepository : IRepository
{
public void Create() { }
public void Read() { }
public void Update() { }
public void Delete() { }
}
class FileRepository : IRepository
{
public void Create() { }
public void Read() { }
public void Update() { }
public void Delete() { }
}
#endregion
}