Skip to content

Instantly share code, notes, and snippets.

@alxsimo
Created January 30, 2015 13:46
Show Gist options
  • Save alxsimo/cfb154d0502e683af00b to your computer and use it in GitHub Desktop.
Save alxsimo/cfb154d0502e683af00b to your computer and use it in GitHub Desktop.
[C#] ServiceContainer - Lighweight DI / IoC implementation
using System;
using System.Collections.Generic;
namespace SIMA.Core.Layers.Transversal.IoC
{
/** ServiceAnomalias serviceAnom = ServiceContainer.Resolve<IUniverseFileServiceAdapter>() **/
public static class ServiceContainer
{
static readonly Dictionary<Type, Lazy<object>> services = new Dictionary<Type, Lazy<object>>();
public static void Register<T>(Func<T> function)
{
services[typeof(T)] = new Lazy<object>(() => function());
}
public static T Resolve<T>()
{
return (T)Resolve(typeof(T));
}
public static object Resolve(Type type)
{
Lazy<object> service;
if (services.TryGetValue(type, out service))
{
return service.Value;
}
throw new Exception("Service not found! (ServiceContainer.Resolve)");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment