Showing posts with label Dependency Injection. Show all posts
Showing posts with label Dependency Injection. Show all posts

Monday, October 31, 2016

IOC Container for Tact.NET

Autofac now supports .NET Core, but other IOC frameworks such as Ninject and Unity have yet to port over. While I was looking into IOC frameworks for .NET Core, I had a bad idea...I, for fun, wrote my own Container in Tact.NET!

So, why did I do this? Honestly, it was just a fun academic exercise! I do think that this is a pretty good container, and I intend to use it in some of my personal projects. Would I recommend that YOU use this? Probably not yet, but I would invite you take a look and offer feedback!

Container Design

I have broken the container into two interfaces: IContainer for registration, and IResolver for consumption. There is a abstract class, ContainerBase, that can be inherited to easily create a container that matches other frameworks; for example, I intend to create a IDependencyResolver for ASP.NET.

You may notice that the IContainer does not have any lifetime management methods, that is because ALL of them are implemented as extension methods...

Registrations

To create a new lifetime manager you have to implement the IRegistration interface. There are already implementations for quite a few:

Resolution Handlers

The last part of the container is the IResolutionHandler interface. These resolution handlers are used when an exact registration match is not found during dependency resolution. For example, the EnumerableResolutionHandler will use ResolveAll to get a collection of whatever type is being requested. Another very different example, the ThrowOnFailResolutionHandler will cause an exception to be thrown when no match can be found.

I think that is a pretty good start, but I am hoping that this will continue to grow with time.

Enjoy,
Tom

Sunday, February 21, 2016

Async Cache Repository v2

Three years ago (wow, time flies) I wrote a generic Cache Repository that has become one of my more popular open source projects. It is 2016, so was definitely time to create an async version of that cache repository! This new implementation has all of the same features as the original, only now it is completely async from top to bottom.

CacheRepository.Web

Features

  • Thread Safe GetOrSet
  • Configurable Expiration Enums
  • Transparent Cache Key Management By Type
  • A Web Implementation

NuGet Package and Source

Enjoy,
Tom

Thursday, August 27, 2015

IEnumerable Unity Injection

A few years ago I blogged about how to add Lazy Unity Injection, and then a year after that Unity 3 added that feature. Recently I had to dust off this old code to do something similar...

I wanted to use Unity to inject a collection of registered types into one of my services. To do this directly from the container you would use named registrations and ResolveAll. However if you just try to resolve an IEnumerable of a type in a constructor, then Unity will just try to use Resolve and thus throw an InvalidOperationException.

We can easily "fix" this by registering an extension with our container.

Extension

public class EnumerableContainerExtension : UnityContainerExtension
{
    protected override void Initialize()
    {
        Context.Policies.Set<IBuildPlanPolicy>(
            new EnumerableBuildPlanPolicy(),
            typeof(IEnumerable<>));
    }
 
    private class EnumerableBuildPlanPolicy : IBuildPlanPolicy
    {
        public void BuildUp(IBuilderContext context)
        {
            if (context.Existing != null)
                return;
 
            var container = context.NewBuildUp<IUnityContainer>();
            var typeToBuild = context.BuildKey.Type.GetGenericArguments()[0];
 
            context.Existing = container.ResolveAll(typeToBuild);
 
            DynamicMethodConstructorStrategy.SetPerBuildSingleton(context);
        }
    }
}

Sunday, August 31, 2014

Three steps to wire up your IOC container.

How can you dynamically and flexibly wire up your inversion of control container? Here are three easy steps to consider:

  1. Reflection
  2. Explicit
  3. Configuration

First, use reflection to help wire up your boiler plate or dynamic dependencies. Second, explicitly register and customize any additional dependencies that your application needs Third, use configuration last to dynamically override any of your previous settings, allowing you to make changes to your application in a live environment without having to rebuild or deploy.

Sample Code

Microsoft's Unity offers a last in win container, so if you follow the steps above in order you will have a very flexible configuration for your container!

Sunday, May 25, 2014

Three Things that all Applications MUST Have

This is the first in a three part series:

  1. Three Things that all Applications MUST Have
  2. Three Things that all Applications SHOULD Have
  3. Three Things that all Applications SHOULD WANT to Have

I feel very strongly that when you start a new project you should spend your first day or two just setting up a few basic utilities. For every hour you spend at the beginning of a project setting up these tools you will save yourself days down the line.

1. Logging

What is your application doing? How can you debug it? Will that work in all environments? The go to answer for these questions should always be logging!

I am constantly amazed at how many applications do not have a logger. To be fair, most of the time when I do not see a logger it is because the application is small or started out as a one off project. However to me that is all the more reason to just take the time and setup a logger right from a project's inception, then you know it will always be there. Thick client, thin client, or back end service, it should have a logger!

2. Dependency Injection

Dependency Injection is a pattern that drives a lot of best practices: it allows you to loosely couple your modules, forces you to consider the number dependencies any given module requires, and perhaps most importantly it makes your code very testable. The inversion of control that dependency injection provides also enables you to refactor and test in ways that are almost unachievable without it.

It can take a little while to fully understand dependency injection, especially the intricacies of lifetime management, but once you understand the fundamentals you can apply that knowledge to any language and any framework.

3. A Test Project

There is no reason not to have a test project as part of your solution. Regardless of how you feel about Test Driven Development (TDD) as a best practice we should all be able to agree that unit testing does provide value and is a good thing.

I encourage you to start simple: just create a test project with ONE unit test inside of it. Even if you do not have time to write tests right now, just having the project already setup will enable you to write them later. Additionally, just thinking about writing unit tests encourages you to author more testable code; so if absolutely nothing else then just use your test project as a best practices placebo!

Continue reading part 2: Three Things that all Applications SHOULD Have

Enjoy,
Tom

Sunday, February 2, 2014

Understanding Unity Named Registration and ResolveAll

I have a love hate relationship with Microsoft Unity, the dependency injection container.

Unity is a very powerful tool, it is an extensible industrial strength container that comes equipped with a ton of features right out of box. However my big beef with it is how those features are not always discoverable, and often they are less than intuitive.

For example, let's talk about named registration. You can register a type from the container with or without a name. This means you can then ask the container to Resolve just the type itself, getting back the unnamed registration, or you can ask the container to Resolve that type for a particular name. That is great, it is a feature required to register multiple implementations of the same interface.

The ResolveAll method, however, is only for use with named registrations.

There is no way to resolve a collection of both named and unnamed registrations. That is not a bad thing in and of iteself, but it does mean that if you want to register a "default" type you will need to register it twice. (For more help with that see my previous blog post: Understanding Unity Lifetime Managers)

Equally interesting is how ResolveAll returns you an IEnumerable by reference.

This means that that enumerable you get back will dynamically change with registrations being made against the container. This might sound neat, but it raises a few big questions...

Is it thread safe? Nope!
Is that documented? Nope!

Saturday, January 11, 2014

Dependency Injection with SignalR and MVC

Thank you to Isaac Abraham for bringing this solution to my attention!

Do not extend DefaultDependencyResolver

How do you practice inversion of control with SignalR? The official SignalR documentation suggests that you extend the DefaultDependencyResolver base class, and then register that as SignalRs dependency resolver.

This however, can have some nasty side effects! In my case, the ConnectionManager.GetHubContext method was not properly resolving my contexts, and thus I was unable to broadcast messages to my hubs clients.

So then, what is a less obtrusive way to inject your dependencies into your hubs?

Instead register an IHubActivator with the DependencyResolver

A simpler solution is just to register a custom HubActivator with the already existing DependencyResolver. This means that instead of completely replacing the SignalR resolver you are instead adding to it.

The HubActivator is only used when trying to resolve a hub; thus the activator can wrap your container of choice and use it to resolve your hub with its dependencies, while leaving the rest of the SignalR pipeline intact.

SignalR Startup with MVC DepenencyResolver

What does this all mean? It means that once you have your dependency injection setup for MVC, you can then create hubs with dependencies using the same container! This MvcHubActivator will use the default System.Web.Mvc.DependencyResolver to resolve its Hubs:

Friday, December 27, 2013

Understanding Unity Lifetime Managers

I absolutely love inversion of control, it is a best practice that I encourage developers to use in every project that they work on. However, like any great tool, dependency injection can cause serious problems if you do not fully understand it; lifetime management in particular.

As a developer you need to be cognisant of how many instances the container is constructing of your classes. You need to know when singleton is going to consume a transient or non thread safe resource. If you are not careful you can leak memory, share unsafe resources, or just make your garbage collector thrash.

Here is a series of examples regarding how to use lifetime managers in my favorite dependency injection container, Microsoft Unity.

  1. ResolveType
  2. Default Lifetime Manager
  3. TransientLifetimeManager
  4. RegisterInstance
  5. ContainerControlledLifetimeManager
  6. ExternallyControlledLifetimeManager
  7. ContainerControlledLifetimeManager with Multiple Keys
  8. RegisterType for Multiple Interfaces
  9. ContainerControlledLifetimeManager with Multiple Interfaces
  10. TransientLifetimeManager with Multiple Interfaces
  11. RegisterInstance Multiple Times
  12. RegisterInstance Multiple Times with External Lifetime Manager

Wednesday, December 18, 2013

Injectable Dataflow Blocks

I really enjoy working with Dataflows, but I always want to resolve my blocks with dependency injection. Thus I have created some abstract wrapper classes around the sealed ActionBlock and TransformBlock classes. This way your can put my logic into the superclass and inject it's dependencies via constructor injection. Additionally, the action method is public, making it even easier to test your code!

Update: I refactored to ditch the constructor parameters in favor of a new abstract BlockOptions.

Sunday, October 20, 2013

Unit Testing and Dependency Injection, with xUnit InlineData and Unity

Inversion of control is great because it makes your code more testable; but you usually still have to write tests for each implementation of your interfaces. So what if your unit testing framework could just work directly with your container to make testing even easier? Well, xUnit can!

Below we define a custom data source for our xUnit theories by extending the InlineDataAttribute. This allows our data driven unit tests to resolve types via a container, and then inject those resolved objects straight into our unit tests.

Bottom line: This allows us to test more with less code!

The rest of post is very code heavy, so I strongly recommend that you start out by taking a look at sections 1 and 2 to get an idea of what we are trying to accomplish. :)

  1. Example Interfaces and Classes
  2. Example Unit Tests
  3. IocInlineDataResolver
  4. UnityInlineDataAttribute

Sunday, February 17, 2013

Cache Repository for MVC

First and foremost, the CacheRepository is NOT web specific!

The CacheRepository library contains the abstract CacheRepositoryBase class, which can be implemented by any caching system that you choose. The CacheRepository.Web NuGet package includes a WebCacheRepository implementation that leverages System.Web.Caching.Cache

CacheRepository.Web

Get all of the source code, unit tests, and a complete MVC4 sample application (preconfigured to include dependency injection with Unity) from GitHub. Or to just jump in and start using it, grab the CacheRepository.Web package from NuGet.

ICacheRepository

The ICacheRepository interface has all the standard Get, Set, Remove and Clear methods. Additionally, these methods have been expanded to include enum parameters to group manage cache expiration.

Best of all, it includes GetOrSet methods. These methods will try to get the value of the specified key, and when it can not find that value it will then be loaded via the passed in Func. A key feature here is the fact that the setter of the GetOrSet will lock on load to prevent redundant data loads. (More details about this below.)

public interface ICacheRepository
{
    object Get(string key);
    T Get<T>(string key);
 
    T GetOrSet<T>(string key, Func<T> loader);
    T GetOrSet<T>(string key, Func<T> loader, DateTime expiration);
    T GetOrSet<T>(string key, Func<T> loader, TimeSpan sliding);
    T GetOrSet<T>(string key, Func<T> loader, CacheExpiration expiration);
    T GetOrSet<T>(string key, Func<T> loader, CacheSliding sliding);
 
    void Set<T>(string key, T value);
    void Set<T>(string key, T value, DateTime expiration);
    void Set<T>(string key, T value, TimeSpan sliding);
    void Set<T>(string key, T value, CacheExpiration expiration);
    void Set<T>(string key, T value, CacheSliding sliding);
 
    void Remove(string key);
    void ClearAll();
}

ThreadSafe GetOrSet

As any good cache should, the CacheRepository is thread safe and can be treated as a singleton.

Even better, the GetOrSet methods lock on set. This means that 10 threads could be trying to load the same cache value simultaneously, but only one will actually trigger a load and set. This helps redundant resource loads and database calls and keep your application running optimally.

private T GetOrSet<T>(string key, Func<T> loader,
    DateTime? expiration, TimeSpan? sliding)
{
    // Get It
    T value;
    var success = TryGet(key, out value);
 
    // Got It or No Loader
    if (loader == null || success)
        return value;
 
    // Load It
    return LockedInvoke(key, () =>
    {
        // Get It (Again)
        success = TryGet(key, out value);
 
        if (!success)
        {
            // Load It (For Real)
            value = loader();
 
            // Set It
            if (value != null)
                Set(key, value, expiration, sliding);
        }
 
        return value;
    });
}

Configurable Expiration Enums

Instead of being forced to set each of your cache expirations separately, you now have the option to use an enum value to group your cache expirations. Enums are available for both absolute expiration and sliding expiration.

You may override the duration of each cache key in your app config; this is really useful for when you want to uniformly modify your cache expirations in your QA or testing environments. Additionally, you may override the CacheRepositoryBase.GetConfigurationValue method to pull this configuration for anywhere you want, not just the ConfigurationManager.

public enum CacheExpiration
{
    VeryShort = 10,     // Ten Seconds
    Short = 60,         // One Minute
    Medium = 300,       // Five Minutes
    Long = 3600,        // One Hour
    VeryLong = 86400    // One Day
}

<configuration>
  <appSettings>
    <add key="CacheExpiration.VeryShort" value="15" />
    <add key="CacheExpiration.Short" value="90" />

ByType Extensions

Transparent cache key management is offered through a series of ICacheRepository extension methods. This makes caching even easier, as you don't need to worry about cache key collisions.

Using these extension methods, you many cache a Cat object with an Id of 1 and a Dog object with an Id of 1 in the same manner. The extension methods will create a key prefix based on the type and then use the specified identified as the suffix.

[Fact]
public void SameKeyDifferentType()
{
    var setCat = new Cat { Name = "Linq" };
    CacheRepository.SetByType(1, setCat);
 
    var setDog = new Dog { Name = "Taboo" };
    CacheRepository.SetByType(1, setDog);
 
    var getCat = CacheRepository.GetByType<Cat>(1);
    Assert.Equal(setCat.Name, getCat.Name);
 
    var getDog = CacheRepository.GetByType<Dog>(1);
    Assert.Equal(setDog.Name, getDog.Name);
}

Web Implementation & Dependency Injection via Unity

The CacheRepository.Web NuGet package includes a WebCacheRepository implementation that leverages System.Web.Caching.Cache. This is a very simple, but very effective, production ready implementation of the CacheRepositoryBase.

It should also be noted that this implementation is not only useful in ASP.NET, the System.Web.Caching.Cache is located in the System.Web library, but it still available outside of a web context. This means that this implementation can be used in other applications, including but not limited to Windows Services.

public class WebCacheRepository : CacheRepositoryBase
{
    private readonly Cache _cache;
        
    public WebCacheRepository()
    {
        _cache = HttpContext.Current == null
            ? HttpRuntime.Cache
            : HttpContext.Current.Cache;
    }

Wiring the cache repository to be injected into your controllers via Unity is also very easy. Just register the WebCacheRepository for the ICacheRepository interface, and be sure to provide a ContainerControlledLifetimeManager for optimal performance.

To use the implementation below, you will need to include the Unity.MVC3 NuGet Package to gain access to the UnityDependencyResolver.

public static void Initialise()
{
    var container = BuildUnityContainer();
    
    DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}
 
private static IUnityContainer BuildUnityContainer()
{
    var container = new UnityContainer();
 
    container.RegisterType<ICacheRepository, WebCacheRepository>(
        new ContainerControlledLifetimeManager());           
 
    return container;
}

If you missed the links above, here they are again:

Shout it

Enjoy,
Tom

Tuesday, September 25, 2012

Func Injection in Unity

Let your container be your factory. :)

If you are using LinqToSql and dependency injection, then you have probably created a factory with which you create DataContexts. But what if you could just let your IOC Container do that work for you? You can!

If you are using Unity then you can inject a Func<T> of any registered type. Unity will automatically bind the injected Func to the container's resolve method, thus preserving the resource Lifetime Manager.

Example Code

public class FuncInjectionTests
{
    [Fact]
    public void TransientLifetimeFuncIsThreadsafe()
    {
        var container = new UnityContainer();
 
        container
            .RegisterType<IUserService, UserService>(
                new ContainerControlledLifetimeManager())
            .RegisterType<IDataContext, DataContext>(
                new TransientLifetimeManager());
 
        var parallelOptions = new ParallelOptions {MaxDegreeOfParallelism = 100};
 
        Parallel.For(0, 1000, parallelOptions, i =>
        {
            var userService = container.Resolve<IUserService>();
 
            Parallel.For(0, 1000, parallelOptions, j =>
            {
                userService.Update();
            });
        });
 
        Assert.Equal(1, UserService.Count);
        Assert.Equal(1000000, DataContext.Count);
    }
}
 
public interface IUserService
{
    void Update();
}
 
public interface IDataContext : IDisposable
{
    void UpdateUser();
}
 
public class UserService : IUserService
{
    public static int Count;
 
    private readonly Func<IDataContext> _dataContextFactory;
 
    public UserService(Func<IDataContext> dataContextFactory)
    {
        _dataContextFactory = dataContextFactory;
        Interlocked.Increment(ref Count);
    }
 
    public void Update()
    {
        using (var dataContext = _dataContextFactory())
            dataContext.UpdateUser();
    }
}
 
public class DataContext : IDataContext
{
    public static int Count;
 
    public DataContext()
    {
        Interlocked.Increment(ref Count);
    }
 
    public void UpdateUser()
    {
        Trace.WriteLine(Thread.CurrentThread.ManagedThreadId + " - " + Count);
    }
 
    public void Dispose()
    {
    }
}
Shout it

Enjoy,
Tom

Sunday, July 29, 2012

Lazy Unity Injection

Adapting a legacy project to use proper Dependency Injection can be difficult.

Often times your services can not be singletons, and then those dependencies cause chains of other services to require transient lifetimes. Sometimes these service dependency trees can grow deep, and their initialization can become quite expensive. If you are working with a website, those big trees can add up and cost a lot of time and memory with every request.

One way to trim a deep or expensive dependency tree is to inject Lazy types of your services.

Lazy injection will prevent an optional resource from being instantiated until it is actually needed. While this is not a scenario that you want to architect your application into voluntarily, it can be a crucial performance optimization. Have you ever taken a memory dump of your website and found thousands of services floating in memory? I have, and let me assure you, it's not pretty!

LazyExtension for Unity

public class LazyExtension : UnityContainerExtension
{
    protected override void Initialize()
    {
        Context.Policies.Set<IBuildPlanPolicy>(
            new LazyBuildPlanPolicy(), 
            typeof(Lazy<>));
    }
 
    public class LazyBuildPlanPolicy : IBuildPlanPolicy
    {
        public void BuildUp(IBuilderContext context)
        {
            if (context.Existing != null)
                return;
 
            var container = context.NewBuildUp<IUnityContainer>();
            var typeToBuild = context.BuildKey.Type.GetGenericArguments()[0];
            var nameToBuild = context.BuildKey.Name;
            var lazyType = typeof(Lazy<>).MakeGenericType(typeToBuild);
 
            var func = GetType()
                .GetMethod("CreateResolver")
                .MakeGenericMethod(typeToBuild)
                .Invoke(this, new object[] { container, nameToBuild });
 
            context.Existing = Activator.CreateInstance(lazyType, func);
 
            DynamicMethodConstructorStrategy.SetPerBuildSingleton(context);
        }
 
        public Func<T> CreateResolver<T>(
            IUnityContainer currentContainer, 
            string nameToBuild)
        {
            return () => currentContainer.Resolve<T>(nameToBuild);
        }
    }
}

Unit Tests

public interface ITestClass
{
    int HighFive();
}
 
public class TestClass : ITestClass
{
    public static int InstanceCount = 0;
 
    public TestClass()
    {
        Interlocked.Increment(ref InstanceCount);
    }
 
    public int HighFive()
    {
        return 5;
    }
}
 
[TestFixture]
public class TestFixture
{
    [Test]
    public void Test()
    {
        using (var container = new UnityContainer())
        {
            container.RegisterType<ITestClass, TestClass>();
            container.AddNewExtension<LazyExtension>();
 
            var testClass1 = container.Resolve<Lazy<ITestClass>>();
 
            Assert.AreEqual(false, testClass1.IsValueCreated);
            Assert.AreEqual(0, TestClass.InstanceCount);
 
            Assert.AreEqual(5, testClass1.Value.HighFive());
            Assert.AreEqual(true, testClass1.IsValueCreated);
            Assert.AreEqual(1, TestClass.InstanceCount);
 
            var testClass2 = container.Resolve<Lazy<ITestClass>>();
 
            Assert.AreEqual(false, testClass2.IsValueCreated);
            Assert.AreEqual(1, TestClass.InstanceCount);
 
            Assert.AreEqual(5, testClass2.Value.HighFive());
            Assert.AreEqual(true, testClass2.IsValueCreated);
            Assert.AreEqual(2, TestClass.InstanceCount);
        }
    }
}
kick it on DotNetKicks.com

Enjoy,
Tom

Tuesday, September 27, 2011

Unity.MVC3 and Disposing Singletons

Recently I was having a conversation with a friend where I was able to articulate my thoughts on dependency injection more eloquently than I ever had before. In fact, I may have phrased this better than any nerd in the history of programming. That's a bold statement, so you be the judge:

"I didn't just swallow the inversion of control kool-aid, I went on the I.V. drip."

Unity.Mvc3

I recently starting working on a new project where they wanted to use Microsoft's Unity for their DI framework. It's not the exact flavor of IOC container would have chosen, but I am all for best practices regardless of specific implementation.

Important side note about MVC3: There is a new way to wire up for dependency injection. MVC now natively exposes a System.Web.MVC.DependencyResolver that you can set to use your container. This means that you no longer need to create a custom MVC controller factory to inject your dependencies.

While researching how best to implement Unity in my MVC 3 project, I came across Unity.Mvc3 by DevTrends. (Here is a little overview.) It's a great project for all the right reasons:

  1. It's up to date.
  2. It's lightweight.
  3. It solves pre-existing issues.

Note that last point. There are a lot of wrappers out there, and a lot of simple copy paste code snippets, but I really appreciate when someone goes out of their way to do more than just write their own version of something. To be specific, unlike many of the alternatives Unity.Mvc3 works with IDisposable dependencies, and that just happens to be a requirement of the project that I am working on.

Also, DevTrends get's additional bonus points for deploying their solution as a NuGet package!

Disposing Singletons with Application_End

I did find two small problems with Unity.Mvc3:

First and foremost, singleton dependencies (anything registered with ContainerControlledLifetimeManager) were not being disposed. This was easy enough to fix however, I just wired up a dispose call to my Bootstrapper in the MvcApplication's Application_End method.

Second, the NuGet package's initialize method was spelled wrong. I actually view this is actually a good thing, because it means that I am not the only person who makes spelling errors in code that they opensource! HA HA HA!

Bootstrapper Example

public static class Bootstrapper
{
    private static IUnityContainer _container;
 
    public static void Initialize()
    {
        _container = BuildUnityContainer();
        var resolver = new UnityDependencyResolver(_container);
        DependencyResolver.SetResolver(resolver);
    }
 
    public static void Dispose()
    {
        if (_container != null)
            _container.Dispose();
    }
 
    private static IUnityContainer BuildUnityContainer()
    {
        var container = new UnityContainer();
        // TODO Register Types Here
        container.RegisterControllers();
        return container;
    }
}
 
public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
 
        Bootstrapper.Initialize();
    }
 
    protected void Application_End()
    {
        Bootstrapper.Dispose();
    }

Enjoy,
Tom

Friday, July 29, 2011

Zen and the Art of Dependency Injection in MVC

Let me start off on a modest note: I am not an expert on dependency injection.
I am, however, certain of the value that it provides.

TDD

After having engaged in the same conversation time and time again, I have become convinced that there is indeed "one simple way to get any developer to write better code." That is because every developer, Junior or Senior, C# or Java, can always engage in more Test Driven Development with Dependency Injection. These are best practices that we can all agree on and that will always result in better and more maintainable code.

If you are already doing TDD with Dependency Injection, keep it up and help spread the word! If you are not, it's time to start. On the plus side, thanks to tools like NuGet, it has never been easier to get started with all of these new fun techniques. :)

Dependency Injection

Dependency Injection is a universally accepted best practice for a number or reasons, not the least of which is how easy it makes unit testing. You should be able to test one section of code without having to rely on the other 99% of your application. By injecting dependencies you are able to control what code is being tested with pin point precision.

A little ant can't move a lake, nor should it want to. However with a little help from a good surface tension framework, it can easily move a drop of water.

MVC

The MVC architecture provides you with a consistent entry point into your code: controller actions. All requests come in and get processed the same way, always passing through a consistent set of action filters and model binders. Right out of the box the MVC model binders are already injecting models straight into your controllers, so why not take it one more step forward and inject your services too?

My controller actions almost always need two things: 1) a model and 2) a service to process that model. So let the MVC model binder manage the RequestContext and inject your model, and let a DI framework manage the logic by injecting your service.

NuGet

To get started (after having installed NuGet) you need look no farther than Tools -> Library Package Manager -> Manage NuGet Packages. If you search for Ninject, a MVC3 specific package will come up that can install itself straight into your MVC3 project and get you going in mere seconds.

Ninject is just one choice of Dependency Injection framework, and it has great documentation. If you would prefer something else then just pick your flavor of choice and keep on moving.

Example

Create your controllers, models and services like normal, and update your controller to take in a service dependency through it's constructor.

public class CalculatorController : Controller
{
     public ICalculatorService CalculatorService {get; private set;}
     public CalculatorController(ICalculatorService calculatorService)
     {
         CalculatorService = calculatorService;
     }

Then all that you have left to do is create a model that binds the service type to it's interface...

public class MvcExampleModule : NinjectModule
{
     public override void Load()
     {
         Bind<ICalculatorService>().To<CalculatorService>();
     }
}

...and load that in the static RegisterServices method.

public static class NinjectMVC3
{
     private static void RegisterServices(IKernel kernel)
     {
          var module = new MvcExampleModule();
          kernel.Load(module);
     }

That's it. That is all that you have to do to start using Dependency Injection.
Want proof? Download the sample application.

Enjoy!
Tom

Real Time Web Analytics