You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
1.3 KiB

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);
}
}
}