parent
2a2319833a
commit
b469188f28
@ -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); |
||||
} |
||||
} |
||||
} |
@ -1,8 +1,8 @@ |
||||
using System; |
||||
|
||||
namespace Samples |
||||
namespace Samples.StringLength |
||||
{ |
||||
class StringLength |
||||
class StringLengthSample |
||||
{ |
||||
public static void Sample() |
||||
{ |
Loading…
Reference in new issue