Is this Better than Constructor Injection?

So after I finished my post on property injection I thought of something, maybe I shouldn’t use constructor injection for my classes.  Maybe, I can just use lazy properties that would call my IoC (Ninject) Kernel to instantiate the object.  So instead of defining a constructor like this:

public IAccountService Service { get; set; }

public AccountController(IAccountService service)
    Service = service;

I could just have a property Service do the work like this:

public IAccountService Service
        return (IAccountService) Kernel.Get(typeof (IAccountService));

If I get rid of all my constructor parameters then I won’t need to change my ControllerFactory to use the Ninject Factory.  This keeps looking better and better.

What do you think?  I keep reading everywhere that construction injection is the way to go.  But why complicate my constructor when I can have the properties do the heavy lifting?  I would love to hear what you think.

Property Injection in ASP.NET MVC with Ninject

I got a design challenge with mvc.  I want to keep track of the currently logged in user in the session because I don’t want to hit the database every time I need to get the username or id for a query.  And I have all my controllers inherit from a base controller named BaseController.  So, I added a CurrentUser property to the BaseController and I want it to automagically work without the derived controllers having to do anything.  Here is a class diagram to help clarify:


The CurrentUser Property needs to look something like this:

public User CurrentUser
        var key = "currentuser";
        if (Session[key] == null)
            Session[key] = /*get user from database some how*/;
        return (User) Session[key] ;

This looks simple enough but it is not.  The reason it is not simple is because to get the current user I have to call Membership.Provider.GetUser from the BaseController.  The problem with that is that it creates a dependency on the MembershipProvider class which I don’t want to have, because it will make testing very hard.

One obvious solution was to add the MembershipProvider (which is an abstract class) to the BaseController’s construct and then pass a mocked instance during testing…  The problem with this design is that now my BaseController will be forced to have a parameterized constructor which means that I have to change the code in all the derived controllers to handle that and pass the appropriate instance of MembershipProvider.  Sounds like a code smell.

My solution was to create the MembershipProvider class using my IoC container – in this case, my Ninject Kernel.  This allows me to inject a SqlMembershipProvider in development and runtime and inject a mocked provider in testing.  So the final CurrentUser property looks like this:

public User CurrentUser
        var key = "currentuser";
        if (Session[key] == null)
            var Provider
                = (MembershipProvider)

            Session[key] = AppHelper.CreateUserFromMembershipUser
                            (Provider.GetUser(User.Identity.Name, true));
        return (User) Session[key] ;

If you have been paying attention, you are probably wondering  what is this “Kernel” thing.  Well Kernel is an instance of the Ninject Kernel which itself was injected into the BaseController class like this:

public IKernel Kernel { get; set; }

I could have done this differently.  For example, I could have injected the provider itself using property injection like this:

public MembershipProvider Provider { get; set; }

The only problem is that the provider isn’t needed by all the derived classed and I didn’t want to have a public property in the base class that would hardly be used anywhere else.   On the other hand Kernel could be globally used to instantiate an object.

What do you think?  Is this the way to do it?  Is there a better way?

Mocking and Dependency Injection in ASP.NET MVC

Here is the situation, my controller constructors take multiple interfaces as parameters.  I do this in order to use constructor injection which allows me to inject the controllers with mocked objects in my unit tests.

For example, my AccountController takes IEmailService, IFormsAuthentication and MembershipProvider (abstract class) as parameters.

During my testing, I want to mock the email, authentication and membership calls.  For example when the user calls FormsAuthentication.Login, I don’t really care if actual call succeeded but rather that my login action works appropriately in the case FormstAuthentication.Login succeeds (or fails).  I just want to mock that call.

I started off creating a few tests and slowly they have grown to several.  There was a lot of repeated code in my unit tests and to be a good citizen of the DRY universe, I needed to refactor the code.

For IoC, I initially started with StructureMap but now I am using Ninject

I created this module to bind my interfaces to mocked instances.  It looks like this:

internal class TestModule : StandardModule
    public override void Load()

Notice that I bind the interfaces to actual instances and not classes.  These instances are declared in a global static class that will be accessed from my unit tests.  As you can tell from the name, they are all mocked objects (I am using Moq).  Here is how the MockEmailService looks (all the others are declared the same way):

internal static class MyMocks
    private static Mock<IEmailService> _mockEmailService;
    public static Mock<IEmailService> MockEmailService
            _mockEmailService = _mockEmailService ?? new Mock<IEmailService>();
            return _mockEmailService;


So all this is good to setup Ninject and create my mocks.  Now I want to easily and generically create a controller, so I can quickly create unit tests.  In order to do that, I created a TestControllerFactory class that basically creates a controller with all the appropriate dependencies injected.

   1: internal static class TestControllerFactory
   2: {
   3:     private static IKernel _kernel;
   4:     public static IKernel Kernel
   5:     {
   6:         get
   7:         {
   8:             if (_kernel == null)
   9:             {
  10:                 var modules = new IModule[] { new TestModule() };
  11:                 _kernel = new StandardKernel(modules);
  12:             }
  13:             return _kernel;
  14:         }
  15:         private set
  16:         {
  17:             _kernel = value;
  18:         }
  19:     }
  21:     public static T GetControllerWithFakeContext<T>(string httpMethod) 
  22:         where T : Controller
  23:     {
  24:         var con = Kernel.Get<T>();
  25:         con.SetFakeControllerContext();
  26:         if (con != null) con.Request.SetHttpMethodResult(httpMethod);
  27:         return con;
  28:     }
  30: }

In line #10, I use the TestModule class mentioned above to setup the Ninject Kernel.  In lines #21 to #28, I create an instance of T which must be of type Controller from the Kernel which will automatically create the Controller with all the mocked objects.  In line #25 and #26, I just set a fake/mocked context and the Http Method for the request (more info here).

Now my unit tests are very clean and easy to setup.    Using MbUnit as my unit test framework, here is a unit tests that tests the reset password functionality.

   1: [Test]
   2: public void ResetPasswordQuestion_Should_Send_Email_On_Success()
   3: {
   4:     var newpassword = "newpassword";
   5:     MyMocks.MockMembershipProvider
   6:          .Expect(p => p.ResetPassword(username, answer))
   7:          .Returns(newpassword);
   8:     MyMocks.MockEmailService
   9:          .Expect(m => m.SendPasswordReset(username, newpassword));
  11:     var ac = TestControllerFactory
  12:                 .GetControllerWithFakeContext<AccountController>("POST");
  14:     var results = ac.ResetPasswordQuestion(username, question, answer);
  15:     //write some asserts in here to make sure things worked
  17:     //verify all mocks
  18:     MyMocks.MockMembershipProvider.VerifyAll();
  19:     MyMocks.MockEmailService.VerifyAll();
  20: }

Line #5: I mock the ResetPassword call on the membership provider and tell it to return the new password

Line #8: I mock the SendPasswordReset method on the email service

Line #11: Get an instance of AccountController from the Ninject Kernel

I just write some code to make sure the expected results took place and that my mocks were properly exercised and that’s pretty much it.  No need to have an SMTP server working to test this, no need to have a database, no need to have an authentication method, no need to implement the interfaces or write dummy methods.

I am like a kid in a candy store with all these things: mocking, dependency injection, inversion of control, unit testing…  I am loving it.

So what do you think?  Is this a good way to go about it?  Is there a better way and what is it?

PDC 2008, Sponsorship Opportunity

I am not a salesman which is good, because I can’t sell cold water in hell.  But I am a professional developer and REALLY want to go to PDC 2008.

Since 1991, the Professional Developers Conference (PDC) has been Microsoft’s premier gathering of leading-edge developers and architects. Attend the PDC to understand the future of the Microsoft platform and to exchange ideas with fellow professionals. You’ll learn about upcoming products, meet Microsoft’s leaders and top engineers, write some code, and be inspired! Unplug for a few days and think about the future.

Unfortunately, it is freaking expensive and I got an engagement and a wedding to pay for, plus I have an interesting employment situation.

What should a dedicated/fanatic geek do?  Well, I am selling myself.  Get your mind out of the gutter, that’s not what I am talking about.

To clarify, I am asking you to sponsor my trip to PDC.  “What do I get out of it?”  I hear you ask yourself.  Well, here is what you get:

  1. I will add your name (or company’s name) and a link to your site to an online list of sponsors.
  2. I will blog about the conference and mention your product/company/service frequently (free publicity)
  3. You will have my sincere gratitude

So why not be charitable, get some cheap publicity and be happier than I am (it has been proven that givers are happier than takers).  So you want to find happiness?  Give me some money.  It’s all for a good cause.

All you have to do is click the “Donate” button above.

List of sponsors will show up here:

Jane Doe from (example)

Is Microsoft Buying the Community?

I love the blogosphere – specially for technical information and news.  My guess is that probably 75% of my “reading” comes from blogs and the rest from magazines such as MSDN, aspnetPRO, Visual studio Magazine, etc…  (plug: my article just made the cover story on asp.netPRO)

As a .net developer, I read these blogs:

  1. Scott Hanselman – very ALT, check his tool list
  2. Phil Haack – Great MVC content and a cool last name 🙂
  3. Scott Gutherie – the alpha dog and must-read blog
  4. Rob ConeryMVC storefront series kicks ass
  5. Matt Berseth – the best looking demos and loves jQuery

There are a lot more but these are the ones at the top of my stack.  You can see all the dev feeds I subscribe to over here.

My point is that a lot of people read the above blogs and are influenced by them.  The problem is that many of these bloggers were not affiliated with Microsoft and some actually were very critical of Microsoft, but now they work there (Matt doesn’t).  To be honest, for the most part, they all seem objective and to an extent critical of Microsoft.  But how long will that last?

It’s ok for me to say something negative about the IE team, because I don’t work for Microsoft.  But if I work down the hall from the entire, that will make for a very uncomfortable elevator ride.  So, I might be inclined to tone down my criticism or even entirely eliminate it (and that is not a good thing).

I am really glad to have the likes of Rob Conery and Scott Hanselman working for Microsoft and helping the company innovate.  But it just seems that lately Microsoft has been hiring a lot of the dissidents.  So if you want to work for Microsoft, create a blog and start criticizing.  Don’t get me wrong though, these guys are very talented (VERY), so you have to have something of value to say.

I got a job offer from Microsoft several years ago and as much as I would have loved to work for them, I couldn’t.  I couldn’t do it because it required moving to Redmond.  Several of the guys mentioned above don’t even live in Redmond – Rob Conery lives in Hawaii (how lucky) and Scott lives in Oregon.  This just tells you that Microsoft is bending backwards to acquire these alpha geeks.

So, who will be hired next?  Ayende RahienJeff Atwood from Coding Horror?  Is this a good strategy on Microsoft’s side?

And if you guys are reading this post, I would like to hear your opinion.  How will you stay objective?  Will you still call out Microsoft publicly?  Or are you going to be on the defensive and be a mouthpiece for the mothership?

Off topic: Why the hell are 109 THOUSANDS people reading coding horror???

Fine Print: I am a huge Microsoft fan but have been disappointed by the lack of recent innovation (except for mvc)

Ninject: Killer IoC

In my previous post, The Best IoC Container, I decided to go with StructureMap as the framework of choice.  I received a comment telling me to check out Ninject and then a day or two after, I saw Corey Gaudin’s post on using Ninject with MVC, so I decided to try it out.

It wasn’t too hard to get up and running in mvc.  Corey’s post was a good starting point but I was too lazy to type all his code in, I wrote my own.  It was pretty easy to get Ninject to work.

I basically created a NinjecteControllerFactory class that inherits from the DefaultControllerFactory and overrode a couple of methods.  The class looks like this:

public class NinjectControllerFactory : DefaultControllerFactory
    private IKernel _kernel;
    public NinjectControllerFactory(params IModule[] modules)
        _kernel = new StandardKernel(modules);

    protected override IController GetControllerInstance(Type controllerType)
        return _kernel.Get(controllerType) as IController;


Then in my Gloval.asax.cs file, I called this code to setup Ninject.

IModule[] modules = new IModule[] { new WebModule() };
ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory(modules));


The WebModule module has my configuration and looks like this:

public class WebModule : StandardModule
    public override void Load()


Of course, you can create as many modules as you want to configure your application and pass them in the controller Factory.

This code was working fine for me and then Nate Kohari mentioned that there is a Ninject.Framework.Mvc extension that allows me to easily integrate Ninject into the MVC pipeline.  So, I decided to download the code, build it and use it.  I initially had some issues because it was referencing a different version of the core dll, so I had to rebuild that as well.

I changed my Global.asax.cs file to the following:

public class GlobalApplication : NinjectHttpApplication
    protected override void RegisterRoutes(RouteCollection routes)

            "Default",                                              // Route name
            "{controller}/{action}/{id}",                           // URL with parameters
            new { controller = "Home", action = "Index", id = "" }  // Parameter defaults

    protected override IKernel CreateKernel()
        IModule[] modules = new IModule[] { new AutoControllerModule(Assembly.GetExecutingAssembly()), new WebModule() };
        return new StandardKernel(modules);

Initially I was getting errors when navigating to an injected controller, which was fixed by add the AutoControllerModule to my modules and passing it the current assembly.

So far Ninject is looking great, the API is fluent and very discoverable and the contextual binding is very slick.  So I am going to stick with it for now and see how it goes.  The documentation seems pretty good and the Nate is very responsive in the Google Group.

The Best IoC Container?

As I previously mentioned in my post “The Best JavaScript Library“, I am in the process of developing an application/writing a book.  I will be using MVC and a TDD approach to the application and book.  As I have done with the JavaScript framework selection, I decided to look around and evaluate/review my options for an Inversion of Control (IoC) Container.

Naturally, my research lead me to a post by Scott Hanselman (see it here) which lists some of the more popular IoC and dependency injection frameworks out there.


I started of looking at Spring.Net and was very impressed by its features, samples/tutorials and documentation but it felt like it would be too much for this project and the learning curve seemed somewhat steep.  Its configuration syntax also looked very verbose.  But if you want to learn more there is a good article over here.

Castle Windsor

It looked easier to learn/use than but there getting started section was incomplete even though Scott says that it is well documented.  So that was a little discouraging.


I really liked there syntax and looked really easy to use and figure out, but the documentation was very limited.  It was just a bunch of wiki pages in Google Code.  Though, they did have instructions on how to integrate it with MVC


Initially, I learned about structure map from a post by Phil Haack’s and I kind of liked it right away.  It was easy to pick up and figure out and Phil’s example helped to get me started quickly.  I checked there website and it has an impressive list of features and is well documented.


PostSharp is really cool but is not an IoC container.  It is a policy injector and a really easy way to do Aspect Oriented Programming (AOP).  Rather than trying to explain what exactly it does and screw it up, take a look at the “About PostSharp” page.  Even better check out this “getting started” walkthrough – you will be very impressed.

Must Pick One

I know there is a lot more IoC containers out there (which I glanced over), but these were sufficient for me.  Initially, I thought about using AutoFac but when I started to actually use it and ran into some issues, the documentation was not helpful at all.

I have decided to go with StructureMap as my IoC Container and dependency injector.  I might also use PostSharp to implement logging and tracing as aspects – there is no cleaner way.

Helpful Links

For a good explanation of IoC Containers and the Dependency Injection patter, read this article by Martin Fowler.

This also a good explanation that might help you understand IoC Containers.

You should definilty take a look Matthew Podwysocki’s comparison of the different IoC containers out there and their different (or rather similar) configuration and syntax.

Books you must Read

Applying Domain-Driven Design and Patterns

And Martin Fowler’s indispensable reference for software patterns Patterns of Enterprise Application Architecture

Validate my Choice

What do you think of my choice?  Does it really matter which one I go with?  Do you prefer a different IoC container and why?

Time to choose a unit testing framework… I love choices!!!

[poll id=”3″]