Small Dependency Injection Framework with Lambda Expressions

Hi everyone, I was evaluating some frameworks for Dependency Injection for a given project here in the company. Frameworks such as Ninject and Unity are very good, but four needs, to 'big'. So we came up with a more 'minimalist' solution.

Based on the Service Locator pattern, we have create the following and quite small service registry:

public sealed class ServiceRegistry
{
    private static readonly Dictionary<Type, Func<Object>> Services = new Dictionary<Type, Func<object>>();

    public static T Resolve<T>() where T : class
    {
        var type = typeof (T);
        if (Services.ContainsKey(type))
            return Services[type]() as T;
        return default(T);
    }

    public static void Bind<T>(Func<T> expression) where T : class
    {
        var type = typeof (T);
        if (Services.ContainsKey(type))
            Services.Remove(type);
        Services.Add(type, expression);
    }
}

 

Using lambda expressions we can bind dynamic type resolvers for our interfaces with no problems and, if necessary, using runtime elements such as configuration parameters and session values.

So, how we use it? It is very simple and straight forward, we just need to bind the types in our application initialization and when required ask for the registry to resolve it (please see the following example):

protected void Application_Start()
{
    //Simple type binding
    ServiceRegistry.Bind<IEmailService>(() = new SmtpEmailService());

    //'Complex' binding using environment variables
    ServiceRegistry.Bind<IIdentityVerifier>(() => {
        var session = HttpContext.Current.Session;
        return new MockIdentityVerifier(session["current-user"]);
    });
}

 

The use would be as simple as:

//...
var identityVerifier = ServiceRegistry.Resolve<IIdentityVerifier>();
identityVerifier.Verify(user);
//...

 

I hope you all enjoy!


Thank you,

Eduardo

Published Monday, December 10, 2012 3:22 PM by edurdias

Comments

No Comments

Leave a Comment

(required) 
(required) 
(optional)
(required)