di injection
This commit is contained in:
58
MySolution/ConsoleApp/Samples/DISample.cs
Normal file
58
MySolution/ConsoleApp/Samples/DISample.cs
Normal file
@@ -0,0 +1,58 @@
|
||||
namespace Samples.DI
|
||||
{
|
||||
class DISample
|
||||
{
|
||||
public static void Sample()
|
||||
{
|
||||
DIContainer container = new DIContainer();
|
||||
container.Register<IService, Service>();
|
||||
|
||||
Client client = new Client(container.Resolve<IService>());
|
||||
client.Run();
|
||||
}
|
||||
}
|
||||
|
||||
public interface IService
|
||||
{
|
||||
void DoSomething();
|
||||
}
|
||||
|
||||
public class Service : IService
|
||||
{
|
||||
public void DoSomething()
|
||||
{
|
||||
Console.WriteLine("Service is doing something...");
|
||||
}
|
||||
}
|
||||
|
||||
public class Client
|
||||
{
|
||||
private readonly IService _service;
|
||||
|
||||
public Client(IService service)
|
||||
{
|
||||
_service = service;
|
||||
}
|
||||
|
||||
public void Run()
|
||||
{
|
||||
_service.DoSomething();
|
||||
}
|
||||
}
|
||||
|
||||
public class DIContainer
|
||||
{
|
||||
private readonly Dictionary<Type, Type> _typemappings = new Dictionary<Type, Type>();
|
||||
|
||||
public void Register<TInterface, TImplementation>()
|
||||
{
|
||||
_typemappings[typeof(TInterface)] = typeof(TImplementation);
|
||||
}
|
||||
|
||||
public TInterface Resolve<TInterface>()
|
||||
{
|
||||
Type implementationType = _typemappings[typeof(TInterface)];
|
||||
return (TInterface)Activator.CreateInstance(implementationType);
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user