Created
February 7, 2013 06:35
-
-
Save deapsquatter/4728991 to your computer and use it in GitHub Desktop.
IOC
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.Concurrent; | |
namespace IOC | |
{ | |
public sealed class IocContainer | |
{ | |
ConcurrentDictionary<Type,Lazy<Object>> container = new ConcurrentDictionary<Type, Lazy<Object>>(); | |
public static readonly IocContainer Default = new IocContainer(); | |
static IocContainer() | |
{ | |
} | |
/// <summary> | |
/// Registers the service. | |
/// </summary> | |
/// <returns><c>true</c>, if service was registered, <c>false</c> otherwise.</returns> | |
/// <typeparam name="T">The 1st type parameter.</typeparam> | |
public bool RegisterService<T>() where T : new() | |
{ | |
return RegisterService(typeof(T), () => new T()); | |
} | |
/// <summary> | |
/// Registers the service. | |
/// </summary> | |
/// <returns><c>true</c>, if service was registered, <c>false</c> otherwise.</returns> | |
/// <param name="type">Type.</param> | |
/// <param name="factoryMethod">Factory method.</param> | |
public bool RegisterService(Type type, Func<Object> factoryMethod) | |
{ | |
return container.TryAdd(type, new Lazy<Object>(factoryMethod)); | |
} | |
/// <summary> | |
/// Finds the service. | |
/// </summary> | |
/// <returns>The service.</returns> | |
/// <typeparam name="T">The 1st type parameter.</typeparam> | |
public T FindService<T>() | |
{ | |
Lazy<Object> res; | |
if (container.TryGetValue(typeof(T) , out res)) | |
return (T)res.Value; | |
else | |
return default(T); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment