Dependency Injection in ASP.NET MVC - Part 2

Welcome to part two of "Dependency Injection in ASP.NET MVC". In part one, we discussed the basics of dependency injection (DI). Please refer to part one here if you need a quick refresher on DI. Now that we have covered the basics of DI, let’s take a look at implementing DI in an ASP.NET MVC application. For the purposes of this article, I will be using ASP.NET MVC 3 and Ninject. In the application, we will create a set of data repositories and inject them into an ASP.NET MVC controller at run-time. This pattern will allow us to cleanly separate our data access logic from our presentation code, and set us up for unit testing. I will be using a simple college course catalog as our domain so we can focus our efforts on the DI implementation. There will be a single view with a simple bulleted list of course numbers and names. All of the data will be mock data defined in the code directly.

First, I am going to create a new ASP.NET MVC 3 web application in Visual Studio 2010. I selected the basic MVC 3 template and ended up with the solution below. I will not be using the Account features of the template, so I went ahead and deleted the Account controller and its associated View folder.

image 1











Now that we have our project in place, we need to pull Ninject into the project. The Nuget package manager makes this a very simple task. There is a Nuget package made specifically for Ninject integration into an ASP.NET MVC project. From the Nuget console, execute the following command to install the Ninject.MVC3 package.

image 2





What did that do for us? Notice that you will now find an App_Start folder in your project. Take a look at the NinjectWebCommon.cs file inside of the App_Start folder. This class is responsible for wiring up the Ninject kernel and ensuring that we can inject dependencies into our controllers automatically. The kernel is the component that actually handles creating instances of objects during the injection process. Take special note of the RegisterServices method. We will come back to this in a moment.

Now we need to create some additional items before we can complete the dependency injection configuration. We will need to define an interface for our course catalog repository called ICourseRepository. Additionally, we will define two implementations of ICourseRepository. Ultimately, we will be injecting an implementation of ICourseRepository into a new controller called CoursesController.  You will notice that in both implementations I am using mock data. In a true implementation, we would have SQL Server or Oracle specific ADO.NET code. Alternatively, this would be a great place to plugin your favorite ORM such Entity Framework or NHibernate. For now, our focus will be on the SqlServerCourseRepository implementation. We will talk about the Oracle version at the end of this article.

Here is the repository code.

image 3





















Notice that we have an interface defined and then two implementations called SqlServerCourseRepository and OracleCourseRepository.  The interface features only a single method called LoadAll. The implementations have some basic hard coded data returning an IList<Course>. Course is a simple two-property class as defined here.


image 4






Next, we need to build a basic controller with a single Index action that returns an IList<Course> as the model. Notice that I have included a constructor in the controller that accepts an instance of ICourseRepository. As I mentioned in part one of this article, we are now set for constructor injection. In this case, our controller has a dependency on ICourseRepository and we are going to use Ninject to “inject” an instance into our controller via the constructor. The Index action is quite simple. We call the LoadAll method of the ICourseRepository instance and return the Index view.

Image 5











Finally, we have some very simple view markup for displaying our courses in a basic un-ordered list.

image 6










There is one final configuration task that we need to complete. Jump back to the RegisterServices method in the NinjectWebCommon class in the App_Start folder. This is where we define or register our interfaces and what concrete implementations they map to. For now, let’s just use the SqlServerCourseRepository. The line below basically says, “If the Ninject kernel receives a request for an instance of ICourseRepository, then return an instance of SqlServerCourseRepository.”

image 7





If we run the application now and navigate to the Course Index, we will see this.


image 9













So what actually happened?

  • We configured our application to use Ninject via the Ninject.MVC3 Nuget package. This package handles nearly all of the Ninject wire-up to support dependency injection into our controllers via constructor injection. For the sake of this example, let’s just say that Ninject is now in charge of our controller factory. This was all part of the code that the Ninject.MVC3 package added to our project.
  •  Via the RegisterServices method, we told Ninject to use an instance of SqlServerCourseRepository whenever an instance of ICourseRepository is required.
  • When we request the Index of the Courses controller, Ninject handles creating an instance of the controller. It inspects the constructor and sees that in order to create a controller instance; it must provide an instance of ICourseRepository. The Ninject controller factory checks the kernel for a binding for ICourseRepository, which it finds. The kernel spins up an instance of SqlServerCourseRepository, and uses it to create the controller instance. 
  • Finally, we call the LoadAll method of our controller instance and return the data to the Index view.

Now that we have gone through all of this trouble to configure our application, you may be wondering why? By adhering to the principle of SoC or Separation of Concerns, we have decoupled our presentation code (Controllers and Views) from our data access code (SqlServerCourseRepository). Notice that in the controller, we only interact with an interface, ICourseRepository. The controller never actually knows what type of repository we are using since the instance is generated and “injected” and run-time.

Suppose our company is acquired by an Oracle-friendly organization. The new CIO decides that SQL Server is inferior to Oracle (yes, this has happened to me more than once) and we need to convert all of our applications to Oracle immediately. In our fictitious example above, we can do this with no impact to the presentation code since we are using a DI container combined with the Repository pattern. We would need to define new repository implementations that are Oracle aware, which we already did at the beginning of this article. Normally, you would not do that until it was actually required; but it works well for this example. Let’s visit the RegisterServices method again. Notice that we are now binding ICourseRepository to OracleCourseRepository.

image 10






And if we run the app again…

imqage 11














We are now serving up data from our mock Oracle repository without changing a single line of controller code! While this was a very simple example, it demonstrates the importance of SoC and just how easily SoC can be accomplished via dependency injection. Dependency Injection frameworks such as Ninject, facilitate SoC in your application architecture via a simple Nuget package and a handful of conventions.

In this article, we used DI to cleanly separate our data access code from our presentation code. This is only one application of dependency injection, albeit a common one. There are many other scenarios that lend themselves well to DI use, including dependency handling for MVC action filters. This is definitely a tool that should be in every developer’s toolbox. For additional reading on DI, I highly recommend the excellent Ninject documentation at 

Happy programming!

About the Author: 

Russell Thatcher is a Software Architect for a medical software provider. He possesses over 10 years of software development experience in a variety of industries, including healthcare, financial, and defense industries. With expertise in the latest Microsoft technologies and Agile development practices, Russell consistently delivers high quality, on target software solutions for his clients.

Posted in: 

The Utopian Data Test Set for Testing SQL Statements

A problem I frequently encounter is how to test data and SQL statements for Oracle, SQL Server, Access or other databases before it’s too late. Most of us test data by using either data that is incredibly simplistic or production data which is far too complex. By incredibly simplistic, I mean something like five rows of data. Incredibly simplistic data is problematic because it uses best-case scenario data, and usually a very limited set at that. Thus the program or data flows using this data usually work just fine. And by working just fine, they fail to turn up any real problems.

The opposite issue is of using data that is too complex such as massive amounts of production data. The problem with production data is that it can cause so many errors that we can never tell where the problem is when something fails. And something always fails, right? There are several things that could fail when using production data: 1) The SQL may be wrong. 2) The data could have problems such as nulls or unanticipated divide by zeros or simply be missing expected data. 3) The linking tables that the data joins to may be missing records. 4) There may be incorrect joins in between tables. In any of these cases, data will fall out or get repeated. Thus the solution is to create large data sets. By large, I mean 1000 rows to 100,000,000 rows.

But for this blog example, let’s use only 10 rows (though normally you might use Excel or something to create 1,000 rows or more). Let’s say you are importing data that joins to a country table. Create 12 rows of simple data that join to a country that you know exists in the country table. The data should look something like this:

Country  Month  Year  Amount

USA         01      2012    10

USA         02      2012    10

USA         03      2012    10

USA         04     2012     10

USA         05     2012     10

USA         06     2012     10

USA         07     2012     10

USA         08     2012     10

USA         09     2012     10

USA         10     2012     10

USA         11     2012     10

USA         12     2012     10


The nice thing about data like this is that we can eyeball it and know that the Amount will total 120. Okay, so now if we join it to the country table, and sum, we should get 120. If we don’t, then we check the county table to see if USA is there. Assuming it is, and we’re still not getting 120 as the sum, then we know that something is wrong in our SQL. But if we were to try the same thing with say 100,000,000 rows of production data, it would 1) take longer to test it, 2) we would have to write more SQL to get a checksum, and 3) if the sum didn’t come out right, then we would have to do a lot more checking and validation to see if the problem was in joining with the country table or a problem in the SQL itself. But with the Utopian Data Set method, we can quickly know whether our process is working or not, and which path to head down to quickly fix it. And if it is working, then we can start playing with real data to see if the numbers tie out. If they don’t, then at least we know that the SQL is good. Then it is a matter of figuring out where the data is causing problems.

And that, my friends, is a topic for another day.

About the Author: 

Narayan Sengupta has been building databases for almost 20 years.  He enjoys spending his spare time with his daughters, traveling, and making presentations about American World War I and World War II history. He can be reached at

Posted in: 

Planning Your Drupal Site

In 2009 we released a whitepaper entitled Building an Enterprise Class Website in Drupal.  The paper covered topics such as: how Drupal is being leveraged at the enterprise-level, planning your site launch for long-term success, assessing and scoping your Drupal project, among many other key topics. Though some of the information might be a bit dated, the core process is still a solid structure to look at when planning your Drupal site.

Here's an outstanding excerpt:

Building an enterprise-level Web site is like preparing for the courtroom: all of your efforts 
are tested upon launch, and you have no second chance to make a first impression. While site builders have the advantage of a “beta” period—and opportunities for refinements over a long run—eventually every public-facing Web site has to face a trial by audience. Verdicts are swift, and appeals unlikely.

So the need to prepare is clear, but not all forms of “preparation” are equal: some devour time with little ultimate result, while others are necessary, but non-obvious. How can you tell which is which? In our experience, effective preparation involves examination of two areas: business goals and technical assets.

Defining your Business’ Goals
The two most common questions we get from prospective clients are:

  • How much is this going to cost?
  • How long will it take?

Surprisingly, the answer to both questions depends more on 
the project’s clarity than on its complexity: in short, ambitious goals that are well-framed are easier and cheaper to achieve than simple goals, poorly framed.

The first step toward clarity is to ask: who is your target audience? You’re seeking not only general demographic information, but also a sense of how its members interact with Web sites. To
 drill deeper: how much do they already use the Internet, and in what ways? How much of your interaction will be “offline”, and how will you tie the two venues together? Are they familiar with online social networking, and would they benefit from it in your site? Are there sites similar to yours that they already use?

This is a good time to exercise your optimism and imagination to their fullest. Try to picture the perfect exchange between your site and your audience; imagine them walking away, smiling and satisfied. Then ask yourself: what can I give them to make them feel that way?

Your decisions at this point will help drive the technical design of your site: a little planning now will prevent the need to develop a custom module two weeks before launch.

Planning Your Drupal Site
The second question to answer is: what assets do you already have? If you already have a Web site, which parts would you like to migrate to the new site? Which have become obstructive or obsolete? What “offline” assets should be brought online? Regardless of your answer, chances are that a fundamental reorganization of assets will make your site clearer, less cluttered, and more friendly. But you can’t start that process until you know exactly what’s on hand.

The last question to answer is: how will you know if you’ve succeeded? Modern Web tools offer comprehensive ways to measure the volume of visitors and track their actions, but far too many administrators treat their metrics program as an afterthought. As a result, they don’t have a sense of what’s working, and their attempts to improve response are scattershot.

So you’ve plotted a course, which is no small feat: fulfillment is impossible without a goal to fulfill. Now it’s time to be sure you have everything needed to execute your plan.

Want more? Download our free whitepaper:  Building an Enterprise Class Website in Drupal.

About the Author: 

Adam Waid is the Director of Marketing at Mediacurrrent, an industry-leader in helping organizations architect custom Drupal websites. Adam is also a MATRIX Alumnus, where he worked closely with the Sales and Recruiting organizations to develop differentiation strategies, create content, and drive CRM and social media initiatives with a single goal in mind - build stronger, more meaningful relationships with our clients. Leveraging new technology, the latest social media trends, and a good mix of traditional marketing, Adam grows online communities.  

Follow Adam on Twitter and Read his Social Media Blog.

Posted in: 

The Agile Project Manager — What’s the Big Deal about Commitment?

As I discussed in my last post, I’m a bit of an “odd bird” when it comes to certain aspects of coaching Agile teams. For example, I like the notion of calling sprints either a success or a failure based on how the team swarmed around and delivered on their Sprint Goal(s). Many agilist’s struggle with using the word failure to connote team performance and delivery—some prefer avoiding it entirely.

Another term that causes angst within Agile circles is the word commitment. Again, I personally like the word commitment. After finishing sprint planning, I like to ask a team to “commit” to their sprint goal. I like the visualization of going “hands-in” as a team—in formalizing their commitment. Sometimes teams even physically do it, which always makes me smile. I see commitment as being a bond within the team to deliver on a realistic goal that they determine as part of sprint planning. It’s a bond extended to the business and generates meaning and focus for the team. But again, I may just be odd and miss the true nature of commitment.

So, what does it mean to be committed?


Let’s start with a definition of the term.  From I found the following definition:

1.  the state or quality of being committed to a cause, policy, or person.
         a.  a pledge or undertaking
2.  an engagement or obligation that restricts freedom of action.

Given that definition, project leadership is always looking for a team to commit to a project—to its target date/schedule, scope, and cost. They’re looking for guarantees from the team to meet the projects’ inception views towards completion targets.

On the surface that doesn’t sound bad—does it? Bringing it back to software development methods, there’s a perceived difference in how “committed” teams are in Waterfall variants vs. Agile variants (Scrum, Extreme Programming, Lean, Kanban, etc.).

Waterfall (is) Committed?

The thought goes that since teams plan their execution thoroughly in Waterfall, to a set of documented requirements, that when the project begins they’re in a clear position to fully commit to the project.

They’re committed to the date, to the scope, and to the costs they’ve estimated. And if there is any “negative discovery” along the way, the team will somehow figure out how to “suck it up”, working harder and longer to meet their “commitment”.  No matter what happens along the way!

You’ll often hear management driving this behavior—reminding the team of their commitment and to work smarter and not harder. There might even be veiled and not so veiled threats, as to what might happen if they fail to…meet their commitment.

Agile (is not) Committed?

Conversely there’s a feeling that Agile teams lack commitment. You hear this coming from nearly every executive, technology leader, and project manager who are adopting agile and struggling with forecasting project outcomes.

This comes from the basic tenet that teams commit to projects incrementally—as they gain more understanding of the work by implementing it in small chunks. That teams narrow in on their delivery target as they gain more understanding and collaborate with their customer. That teams can commit when they’ve made some progress and understand their delivery velocity.

In lieu of simply committing without knowing, Agile teams focus on incremental delivery and incremental commitment; needing some time to truly understand the project complexity and their own capacity. Many misconstrue this prudence and transparency for a lack of commitment. But there’s also a truth to agilist’s struggling with the term.

A quick diversion to the Scrum Guide
Ken Schwaber and publish something called the Scrum Guide. They recently (2011) published an update to the Scrum Guide changing the language used to reflect the team posture at the conclusion of Sprint Planning. Previous language had used “commit”, as in the team would “commit” to the work they identified and planned as part of their sprint.

The updated language changed the word “commit” to the word “forecast”—here’s a copy of the language change that I copied from the FAQ on the site - Development Teams do not commit to completing the work planned during a Sprint Planning Meeting. The Development Team creates a forecast of work it believes will be done, but that forecast will change as more becomes known throughout the Sprint.

This was one of six changes or adjustments that were made within the guide. I bring it up because it amplifies a common reaction in the agile community to the word commitment. At my core, I don’t understand the issue. It’s just a word.

Back to Waterfall vs. Agile Commitment
So are Waterfall teams more committed than their Agile counterparts? In the use of language around project targets and scope, it certainly appears so. But let’s get real. Waterfall projects rarely meet their commitments. I rarely do this, but I’ll bring out some statistics to make the point…

According to the 2009 Chaos Report examining the success rate of IT projects found that – 32% of projects succeeded, 44% were challenged or failed to meet some project goals, and 24% failed completely.

The key point here is the assumption that these were committed teams, yet literally 2/3 of the projects failed in some capacity. So I contend that commitment is simply a word. Not let’s look at commitment from a different angle—probably the right angle.

The Real Nature of Commitment
I don’t think team commitment comes from a methodology or a planning process—particularly for highly complex, technology-driven projects, with tremendous up-side risk because your teams are creating novel solutions to your problems.

Commitment is created by many factors and I don’t pretend to be an expert on it. However, it seems to me that some of the following are crucial to support an environment of commitment—

  • Teams commit to each other; so fostering an environment of teamwork, mutual accountability, trust, and professionalism.
  • Teams commit to exciting and meaningful work; so communicate the ‘why’ and ‘impact’ of their work to inspire the team.
  • Teams commit to solid leaders—leaders who trust them to do their jobs and who provide sufficient support for them to succeed.
  • Teams commit to doing good work. Work that balances competitive delivery against solid designs, creativity, work-life balance, and high quality.
  • Teams commit to providing total honesty and real-time transparency so that their leaders can make congruent adjustments; to leaders that can “handle the truth”.

Wrapping Up

So I still like to instill in Agile teams that Sprints can either “Pass or Fail” depending on their efforts and behaviors and results relative to their sprint goal. And yes, I do expect a team to “Commit To” their plan to meet a sprint goal that they’ve established with their Product Owner.

I feel it’s not the word that is the problem. Instead, the question is—does the environment support the team in the areas I mention above in meeting their commitments? Point being—I don’t see commitment as a team only condition. I think the organization needs to establish a culture and an environment where commitment is supported. Where discovery and adjustment is supported, where honesty and transparency is honored, and where failure is tolerated.

If you have an environment that isn’t supportive, then yes, I can see changing the term and not using it. In that environment, then “forecast” would be a better term…as would dysfunctional. But I’m tremendously disappointed in the organization that can’t make congruent commitments across their teams and then deliver on those commitments.

So call me committed to An Environment of Commitment…

Till next time - Bob

1.    Top 10 Agile Phobias -
2.    Chaos Report reference –
3.    Scrum Guide reference –
4.    Wonderful article on Estimation, Prediction, and Commitment –

About the Author: 

Bob Galen is the Director, Agile Practices at iContact and founder of RGCG, LLC a technical consulting company focused towards increasing agility and pragmatism within software projects and teams. He has over 25 years of experience as a software developer, tester, project manager and leader. Bob regularly consults, writes and is a popular speaker on a wide variety of software topics. He is also the author of the book Scrum Product Ownership – Balancing Value from the Inside Out. He can be reached at

Posted in: 

Is Your Website Future-Ready?

Maybe you already know by now that mobile web is important. There are now more than 100 million smartphone users in the U.S. and the percentage of overall web traffic that comes from mobile users just doubled in 2011.

So what does that mean for your website? If your site isn't optimized for mobile, that's a lot of people that are struggling to get the information they need from you, or worse, that are leaving to find someplace else they can. It can be overwhelming to consider all the possible ways you could try to reach this target audience. One route would be to build a mobile app, but that can be expensive to both build and update an app for several phone types—and then there's the small matter of users being able to find and download it from the app store.

Drupal Mobile

Mobile web seems to be the quickest route. Everyone with a smart phone has access to the web; and all that hard work you did building up your SEO can help mobile users find your site quickly. So how do you prepare your site for mobile users? You could build an entirely separate website using a third party tool, and try to incorporate the most important information into the mobile site. Re-route traffic to, and then struggle to keep your regular website and your new mobile site up-to-date. But device detection isn't perfect, and sometimes mobile users want to see ALL the content on your site, not the abridged version.

What if there was a way to update all your content in one place, and have it display one way to visitors on desktop computers and a different way to users on mobile devices? What if the layout could shape-shift to accommodate tablets of all sizes, and even expand to showcase a wider version for users with large monitors?

Enter the perfect couple: Drupal + Responsive Design. It's no Brangelina, but it still rocks. With Drupal, a powerful, open-source, fully customizable content management system — adding and updating your content is a snap. Photos resize themselves, formatting is taken care of for you, and multiple users can make updates and save revisions. Drupal is also ready to slip into a responsive theme like Omega or the Adaptive Theme. This means that your content is optimized for whatever screen size your visitor has got, and no one leaves grumbling and frustrated. Take a look at some of the most recent responsive sites we've launched with Drupal.

It's the real deal. Mediacurrent recently published a whitepaper, "The Mobile Web with Drupal", that expands on why organizations must move into the mobile arena. Be sure to check it out.

About the Author: 

Kendall Totten is a Drupal Designer & Theming Specialist at Mediacurrent, a Drupal web development agency based out of Atlanta, GA.  Kendall is a graduate from Eastern Michigan University, where she studied Communication Technology and Graphic Design. She worked in the layout and design department at the Eastern Echo newspaper for three years, eventually becoming the Chief of Design. Kendall grew and expanded her role as a graphic designer into Drupal front-end development, support, and client training.

Posted in: