Created
January 30, 2015 13:46
-
-
Save alxsimo/cfb154d0502e683af00b to your computer and use it in GitHub Desktop.
[C#] ServiceContainer - Lighweight DI / IoC implementation
This file contains 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 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