Skip to content

Instantly share code, notes, and snippets.

@deapsquatter
Created February 7, 2013 06:35
Show Gist options
  • Save deapsquatter/4728991 to your computer and use it in GitHub Desktop.
Save deapsquatter/4728991 to your computer and use it in GitHub Desktop.
IOC
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