Files
dotNetStudyWithGPT/MySolution/ConsoleApp/Samples/DISample.cs

58 lines
1.3 KiB
C#
Raw Normal View History

2023-05-11 13:56:53 +09:00
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);
}
}
}