Skip to content

Instantly share code, notes, and snippets.

@ggondim
Last active March 26, 2016 03:02
Show Gist options
  • Save ggondim/e8b28234e1a478925266 to your computer and use it in GitHub Desktop.
Save ggondim/e8b28234e1a478925266 to your computer and use it in GitHub Desktop.
A simple and quick DI container and resolver with Singleton and Transient lifecycles.
// DependencyResolver
// A simple and quick DI container and resolver with Singleton and Transient lifecycles.
// Copyright © 2016 Gustavo Gondim (https://github.com/ggondim)
// Licensed under Creative Commons 3.0 BY
// Instructions:
// - Replace <%namespace%> with your application's namespace.
// - Register instances in DependencyResolver constructor.
// - Split enums and classes into separate files if you want to a better project organization.
using System;
using System.Collections.Concurrent;
using System.Linq;
namespace <%namespace%>
{
public enum Lifecycle
{
Singleton,
Transient
}
public abstract class DependencyResolution
{
public Type Type { get; set; }
public Lifecycle Lifecycle { get; set; }
}
public class SingletonResolution<T> : DependencyResolution
{
public T Instance { get; set; }
public SingletonResolution(T instance)
{
Instance = instance;
Type = typeof (T);
Lifecycle = Lifecycle.Singleton;
}
}
public class TransientResolution<T> : DependencyResolution
{
public Func<T> Construction { get; set; }
public TransientResolution(Func<T> construction = null)
{
Construction = construction;
Type = typeof (T);
Lifecycle = Lifecycle.Transient;
}
}
public static class DependencyResolver
{
private static ConcurrentDictionary<Type, DependencyResolution> _resolutions;
private static ConcurrentDictionary<Type, DependencyResolution> Resolutions => _resolutions ?? (_resolutions = new ConcurrentDictionary<Type, DependencyResolution>());
public static void RegisterSingleton<T>(T instance)
{
while (!Resolutions.TryAdd(typeof(T), new SingletonResolution<T>(instance)))
{
}
}
public static void RegisterTransient<T>(Func<T> construction)
{
while (!Resolutions.TryAdd(typeof(T), new TransientResolution<T>(construction)))
{
}
}
public static T Resolve<T>()
where T : class
{
return Resolutions
.Where(x => x.Key == typeof (T))
.Select(x => x.Value.Lifecycle == Lifecycle.Singleton ? ((SingletonResolution<T>)x.Value).Instance : ((TransientResolution<T>)x.Value).Construction.Invoke())
.Single();
}
static DependencyResolver()
{
// REGISTER YOUR INSTANCES HERE
RegisterSingleton<<%anInterfaceOrBaseType%>>(new <%aTypeOrInheritedType%>();
RegisterSingleton(new <%anotherTypeOrInheritedType%>();
RegisterTransient<<%anotherInterfaceOrBaseType%>>(new <%anotherTypeOrInheritedType%>());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment