ASP.Net, MVC

New ASP.Net MVC Source Drop

Scott Guthrie recently posted about the new ASP.Net MVC Source Preview and I have to tell you that I am really excited about these new bits. Not only have they added the source code for the unit tests with this release but that have added two new features that I think are really going to make life easier.

If you have played around with ASP.Net MVC, or have read articles covering it, you will know that one of the key features to ASP.Net MVC is the support for unit testing in the Presentation tier. Prior to ASP.Net MVC you could perform some unit testing in the Presentation tier but often times you were required to use a record/playback mechanism that did nothing more than record the HTTP request, store the data in some XML or other file format, and allowed you to "replay" the scenario. More times than not, however, the amount of time and effort to test this tier was too much to make it a common everyday task that developers would follow.

In the first few releases of the MVC framework the ability to create and execute unit tests has been made a lot easier and a ton more manageable. The biggest complaints out there were that you had to using a "mocking" framework or stub out the entire HttpContext to test the Controllers. And while Preview 2 of the MVC framework has even made this easier with the IViewEngine and the HttpContextBase class.

Well… now comes the latest bits. Now in the latest drop you don’t need to mock anything or create a fake ViewEngine. This is all thanks the to the ActionResult class which is returned for every method call in a Controller class. Not only does this new class make it even easier to unit test your Presentation tier but it also opens up a bunch of other opportunities since the ActionResult class contains the ViewData object as well.

But wait… it get’s better (boy… do I sound like a late night commercial or what)

This release also contains some changes that have been made to the URL Route Mapping feature. In these bits you can now include characters like "-" and "." in your route. The most impressive example that was given in Scott’s article was the file extension or format example. In this example Scott shows how you can produce a route which would provide an extension to determine the what format to use when rendering the data.

For example, the route "products/browse/{category}.{format}" would pass the "category" and the "format" to the Controller. Now imagine that we use a URI like "products/browse/cars.xml". This would not only tell the Controller to go and get the data for the "cars" category but it would also let us know that the user is expecting this in an XML format. Now consider a URI like "products/browse/cars.json" or "products/browse/cars.yaml". The Controller would be able to determine the right View to execute based on format. Or perhaps we would be able to advantage of the ActionResult and create a Factory which based on the format returns a sub-class of ActionResult which we can filter on.

I can only imagine what they are coming up with for the next drop… if it is anything like this… it’s going to be good.

Standard
.Net, Patterns

Dependency Injection – Why should we care?

In my previous post we covered (briefly) Inversion of Control (IoC) and Dependency Injection. In this post we will discuss why we should use Dependency Injection and how it can improve our every day coding life.

Again… from my previous post we found that we can inject objects and values a particular class is dependant upon through the constructor or through property setters. But this really begs the question of why you would want to do that? Well there are a couple of benefits from doing this:

  1. Identifying dependencies for a particular class becomes easier
  2. Inheritance fully describes dependencies
  3. Dependencies become easier to test, mock or stub

So lets take each of these reasons one by one and give some brief examples. Consider the following class as an example:

Sample Code

As we can see from this simple example the "EmployeeRate" class is dependent upon the "Employee" class. Not only that but we can also see that in order to get the "Employee" class we need to make a call to the database to retrieve the information.

Let’s suppose that someone else is trying to create an instance of this class. Another developer would never know that this class uses the "Employee" class and it might very well be that they are already working an "Employee" class. So if instead we refactor this class to follow the Dependency Injection pattern, anybody would be able to quickly tell that the "Employee" class is indeed a dependent class.

 Refactored Employee Rate Class 

(If you are like me you more than likely wouldn’t stop there. After looking further into the code you might have seen that there is no real need to have a constructor for this class at all. Instead, simply make the two methods static and pass the "Employee" class in as a parameter. For the purpose of this post however… let’s just play along)

Let’s now take a look at how the inheritance model would benefit from using the Dependency Injection pattern.

Let’s once again take the original example and create a new class called "ManagerRate." This class needs to do some things that a normal employee wouldn’t have to do like factor in the number of employees they manage. Regardless of the reason, we need to calculate a managers rate differently then an employee. We could add a "switch" statement or "if … else" condition to apply this logic but… being good little developers we created this class.

Manager Rate Class

Here we can see that it is not clear to the "ManagerRate" class what dependencies the base class requires. Not only that but if we put our "extensibility" hat on for a second we can see that if an employee and a manager are ever broken up to be separate classes then we would have a problem and would more than likely result in a change in logic in both classes. Let’s now see what our "ManagerRate" class would like from our refactored version.

Refactored Manager Rate Class

Now the "ManagerRate" class can clearly see what the dependencies are for the base class. And if we put our "extensibility" hat back on we could see that we might still have an issue if an employee and a manager are separated into two classes but the code change would only need to occur in one class and more than likely it would only require they type to change. If we really wanted to do it up correctly we would create an interface for the "Employee" class.

Finally, let’s look at how testing can benefit from our use of the Dependency Injection pattern.

If we go back to the original example and look at what happened in the constructor we would see that the constructor called a static method on the "Employee" class named "GetById." Suppose now that we want to test the "EmployeeRate" class to ensure that it’s "CalculateSpecialRate" method returned the correct value. How would we go about doing that?

First we would need to make sure that we have a database with valid (or good) data in it for a given "Employee." Normally we would insert a new row in the corresponding table and record the resulting primary key or "id." Then when we ran our unit test we would need to make sure that we pass in the correct "id" to our "EmployeeRate" constructor.

If, however, our data gets deleted, modified, or someone else is running our unit tests in another environment then our tests would fail. It wouldn’t fail because our code is wrong but because the supporting data is missing. So what are we really testing in this scenario… the code or the data?

If we follow the Dependency Injection pattern as we did in our refactored code then we would be able to create reliable and "database proof" unit tests. By passing in a mock or stub of an "Employee" class, the data being used will always be the same and our unit tests will always be testing the code and not the data.

Another benefit that we did not have time to cover is how Dependency Injection is used in Aspect Oriented Programming (AOP). There are plenty of other posts out there that cover AOP that I recommend you read. In short… being able to intercept calls and inject other objects, values, or classes based on the cross-cutting concerns is not only the point behind AOP but dramatically reduces code and increases code reuse.

In this post we covered three out of many benefits to using Dependency Injection. Hopefully the examples drive this point home and starts to make you rethink the way you design and write code in your everyday life.

Standard
.Net, Patterns

Inversion of Control and Dependency Injection

MVC has not only brought about a change in how we think about designing and building web applications on the .Net framework but it has also reminded most of us about the Inversion of Control (IoC) and Dependency Injection patterns. While most of us have used these patterns before (without even knowing about it), I think that it is very important to understand what these patterns are, how to use them, and why they are important not only with MVC but in everyday "coding" life.

IoC and DI are defined and described at length in an article written back in 2004 by Martin Fowler named "Inversion of Control Containers and the Dependency Injection pattern" that I highly recommend everyone read. I am not going to go into great details about these patterns but…

  • IoC means that an object gets other objects that it relies on through an outside source or framework
  • Dependency Injection means that an object gets other objects that it relies on through it’s constructor or set properties

It is safe to say that these are the same but just remember that there is a difference. I have also found that when people or articles have talked about IoC they have been really talking about Dependency Injection. So enough about that… what does it look like?

Let’s start with a simple class which relies on a Data Access class (named "MyDataAccess") to connect to some database…

MyObject class 

Imagine now that the "MyDataAccess" implements an interface named "IDataAccess" and we change the code to reflect that…

Sample MyObject 

But now if our example changes one more time… and this time we add yet another class which implements the "IDataAccess" interface, we would have to add more logic or code to determine which concrete class should be created…

Sample MyObject 

Clearly this is going to be a problem each time we want add a new class which implements the "IDataAccess" interface. Now expand this out to several classes which depend upon an "IDataAccess" object and you start to see the overhead with maintaining that code.

Enter the Dependency Injection pattern where we pass in an "IDataAccess" object as a parameter to the constructor. This then moves the responsibility (or control) of creating the "IDataAccess" object outside of our class or outside of it’s scope.

MyObject class 

So now any time someone creates an instance of this class they can clearly see that it needs or depends upon an "IDataAccess" object. We have also increased the test-ability of our class by being able to pass in stubs or "mock" objects.

In my next post I will cover more of the benefits and show it works amd how it is used in Testing, MVC and LINQ frameworks.

kick it on DotNetKicks.com

Standard
ASP.Net, MVC

ASP.Net MVC Source Code Available… our first test

Scott Guthrie recently posted an article about the ASP.Net MVC Source Code becoming available from the CodePlex website.

I think that this a huge step in the right direction. I would even go as far as saying that this “move” was intentional. If you take a minute and think about what this means… you will see what I am talking about.

With the source code to the MVC library being made available… it is almost like we as developers are being tested. Will we take the source code and make it our own? Will we report back defects and enhancements back to Microsoft to improve this feature? Will we open it up and try to break it and find flaws in the underlying code?

My point being that if we take the right approach as a community and as a team then not only will we (the end users of these features) become more familiar and confident with these bits but our input and feedback will find a larger and more important audience in the long run.

Is that to say that when I (a simple developer in the .Net world) find an issue with the way that they (the developers at Microsoft) implemented some piece of code expect it to be corrected? No. Is that to say that when I feel like there is a feature or method that can make my life easier it will be included in the final release? No.

What it does mean is that I am given a chance to make the community, feature, and the platform as a whole better. Sure… I am only one voice. If my voice is included along with others… it becomes easier to hear. If I am given the chance to work with and validate the feature as a “real world developer” then when the feature or functionality is incorporated… we are the ones to blame if something doesn’t do what the rest of developers feel like it should.

All and all… I feel like this is a tremendous opportunity that is being given. While this would not be considered “open source” by any stretch of the imagination, I (little old me… a simple developer) am being given the chance… to change… Microsoft and the .Net language.

Take a minute and think about what that means to you…
Do you want to be a part of the community or simply consume it?


kick it on DotNetKicks.com

Standard