Last active
August 20, 2020 07:35
-
-
Save ShreyasJejurkar/1fd060e8ace3f1227abe673e26653a9b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
namespace IocContainer | |
{ | |
public class Program | |
{ | |
public static void Main() | |
{ | |
var containerBuilder = new ContainerBuilder(); | |
containerBuilder.For<ILogger>().Use<FileLogger>(); | |
var container = containerBuilder | |
.Build(); | |
var logger = container.Resolve<ILogger>(); | |
logger.Log(); | |
} | |
} | |
public class Container | |
{ | |
public Dictionary<Type, Type> serviceRegistration; | |
public Container() | |
{ | |
serviceRegistration = new Dictionary<Type,Type>(); | |
} | |
public T Resolve<T>() | |
{ | |
if(serviceRegistration.ContainsKey(typeof(T))) | |
{ | |
var implementation = serviceRegistration[typeof(T)]; | |
return (T) Activator.CreateInstance(implementation); | |
} | |
else | |
{ | |
throw new InvalidOperationException("${typeof(T).Name} service is not registered to the container"); | |
} | |
} | |
} | |
public class ContainerBuilder | |
{ | |
private Container _container; | |
private Type serviceType; | |
public ContainerBuilder() | |
{ | |
_container = new Container(); | |
} | |
public ContainerBuilder For<T>() | |
{ | |
serviceType = typeof(T); | |
return this; | |
} | |
public ContainerBuilder Use<T>() | |
{ | |
_container.serviceRegistration.Add(serviceType, typeof(T)); | |
return this; | |
} | |
public Container Build() | |
{ | |
return _container; | |
} | |
} | |
public interface ILogger | |
{ | |
void Log(); | |
} | |
public class SQLServerLogger : ILogger | |
{ | |
public void Log() | |
{ | |
Console.WriteLine("SQL Server logging..."); | |
} | |
} | |
public class FileLogger : ILogger | |
{ | |
public void Log() | |
{ | |
Console.WriteLine("File Logging..."); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
✔️ Compilation completed. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"version": 1, | |
"target": "Verify", | |
"mode": "Debug" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment