Skip to content

Instantly share code, notes, and snippets.

@ShreyasJejurkar
Last active August 20, 2020 07:35
Show Gist options
  • Save ShreyasJejurkar/1fd060e8ace3f1227abe673e26653a9b to your computer and use it in GitHub Desktop.
Save ShreyasJejurkar/1fd060e8ace3f1227abe673e26653a9b to your computer and use it in GitHub Desktop.
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...");
}
}
}
✔️ Compilation completed.
{
"version": 1,
"target": "Verify",
"mode": "Debug"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment