Steve Michelotti

C#, ASP.NET, and other stuff

  Home  |   Contact  |   Syndication    |   Login
  108 Posts | 1 Stories | 410 Comments | 51 Trackbacks

News

View Steve Michelotti's profile on LinkedIn






Google My Blog

What I'm Reading:

Shelfari: Book reviews on your book blog

Tag Cloud


Archives

Post Categories

Image Galleries

Blogs

Code

Publications

Wednesday, November 18, 2009 #

Recently my company just released the first version of a new MVC web site: AlbumCredits.com.  This project, led by Oskar Austegard, is was I consider a highly successful real-world implementation of MVC. In a time when most music these days is downloaded, the production and performance engineers, and recording professionals that work on the music don’t always get credit because there is no CD booklet to look through.  Album Credits is almost like a LinkedIn for recording professionals.  From the about page:  AlbumCredits.com is “A fast, easy way to find production and performance credits from more than one million CDs and LPs.”

We leveraged a ton of great technologies during the development of this solution. To name a few:

  • Custom Controller factory based on StructureMap Inversion of Control (IoC) container
  • jQuery for all AJAX needs
  • T4MVC Templates
  • Data Annotations for Validation
  • xVal for client side validation
  • LINQ to SQL with stored procedures (including a few UDFs) for data access
  • SQL Server 2008 with Full Text Search
  • SQL Server Integration Services for the data feed
  • MvcFutures (functionality that will be baked in to MVC2)
  • Numerous custom HTML Helpers
  • Numerous third party jQuery plug ins including:
    • jQuery UI
    • jQuery Tools:
      • Tabs
      • Scrollable
      • Overlay
    • Tablesorter
    • jQuery Form
    • Jcrop
    • jWysiwyg
  • For unit testing – NUnit and NUnitEx
  • For mocking - Moq

Additionally, on the build server we used:

  • Cruise Control .NET
  • MSBuild
  • FxCop
  • StyleCop
  • NUnit

Album Credit starts with a nice AJAX auto-complete search box:

 

The site is then “deep linkable”. Want to see what engineers worked on a particular album?  What other albums did they work on? Which other artists?  You can literally relate any category together in your searching - think Six Degrees of Kevin Bacon but for the music industry.

 

It’s an example of a site that takes a very cool idea and melds it will a solid technical implementation.  Check it out!


Saturday, November 14, 2009 #

If you’re planning on being at Windows 7 Developer Boot Camp (already sold out) at PDC 09 next week come check out the “Lunch with the MVPs” scheduled from 12:00-1:15. We will be having several tables where you can come over and have (informal) conversations on a wide range of topics including: MVC, RIA, Silverlight, XNA, LINQ, and more.  I will be leading the table “MVC in the Real World” so come check us out.  Hope to see you there!


Thursday, November 12, 2009 #

Thanks to everyone who attended my LINQ to SQL presentation at RockNUG last night.  The code samples can be downloaded here: LINQ to SQL demo code.

As a point of clarification from last night’s Q&A session after the presentation regarding using LINQ to SQL with true POCO classes that do not even have [Column] mapping attributes, you can have a class like this:

   1:  public class Contact
   2:  {
   3:      public int ID;
   4:      public string FirstName { get; set; }
   5:      public string LastName { get; set; }
   6:      public string Title { get; set; }
   7:  }

If you’re using LINQ to SQL with stored procedures then this class (even without the [Column] attributes) will work just fine.  The one catch is that you can *not* have the class itself decorated with the [Table] attribute which is what happened during the Q&A at the end of last night when someone asked me to show it work without attributes.  I commented the [Column] attribute but did not also comment the [Table] attribute on the class level. If I had also commented out the [Table] attribute, however, then I would have run into this (different issue) because of the “extra” HomeAddress and BusinessAddress properties I added to the partial class (so bear that in mind if you test).

If you watch my blog in the next couple of days (or just subscribe to the rss feed) I’ll put up a post dedicated strictly to the various mapping options you have with LINQ to SQL and downloadable code examples of each since the only mapping I showed last night was the attributed-based mapping (e.g., mapping with attributes, mapping with XML, mapping differences with auto-generated SQL vs. stored proces, mapping with true POCO, etc.).  Thanks!


Tuesday, November 10, 2009 #

Tomorrow night I’ll be at RockNUG presenting LINQ to SQL. Yes, LINQ to SQL. Again. In the last 2 years I have presented LINQ to SQL numerous times at various user groups and code camps. Why do I keep getting asked to present LINQ to SQL? Isn’t LINQ to SQL dead? Answer: No.  LINQ to SQL is not dead!

This confusion all started back in October 2008 with a seemingly innocuous post on the ADO.NET team blog discussing the emphasis that Microsoft was going to put into the Entity Framework going forward.  The developer community was immediately up in arms about this post for a variety of reasons.  First, many developers and companies had already made a significant investment in developing with LINQ to SQL.  Secondly, LINQ to SQL is great so why de-emphasize it?  Third, the Entity Framework has had its share of challenges getting acceptance in the development community (and I’m being charitable) so the thought of replacing something “good” with something “not as good” was not met with enthusiasm.

This led to a “clarification message” by the ADO.NET team a few days later in which they clearly state: “LINQ to SQL is not dead.” This post may have been a somewhat weak defense of LINQ to SQL but the message was clear nonetheless. We’ve also seen others from Microsoft strongly advocate LINQ to SQL.  For example, in this MVC presentation at MIX 09, Scott Hanselman states he’s using LINQ to SQL in the demo “because it’s awesome and it’s not dead.” This all leads to a somewhat confusing state of affairs because we find ourselves relying on quotes from a respected Microsoft guru like Scott Hanselman and others in an attempt to translate Microsoft’s marketing approach for their latest data access strategy. After all, one of the longest running jokes is that the last thing Microsoft needs is yet another data access framework.

So how do we make this pragmatic decision for ourselves when deciding on a data access strategy/framework? Although there are numerous data access choices, the top three frameworks that are typically examined are: 1) LINQ to SQL, 2) NHibernate, and 3) the Entity Framework (EF).

The Entity Framework vNext that will be released after .NET 4.0 looks very promising.  Model first, POCO code only, foreign key relationships, and more make me enthusiastic to give EF another run next year.  But…that’s next year. If you’re starting development on a new application today, you might think twice.

NHibernate is a great framework. No dispute there. On it’s own it’s solid but then when you add features such as Fluent NHibernate and LINQ to NHibernate it’s becomes an extremely compelling choice. However, there is a steeper learning curve with NHibernate as compared to some other frameworks such as LINQ to SQL.  Additionally, some organizations (unfortunately) have policies against using open source software which disqualifies NHibernate in those environments.

Then you’ve got trusty ol’ LINQ to SQL. In the last year, LINQ to SQL has continued to provide a solid data access choice. I strongly agree with the numerous points that Ian Cooper made in this post showing support for LINQ to SQL. In short, there are numerous reasons to learn and use LINQ to SQL. Among them:

  • LINQ to SQL is a stable release and has withstood the test for 2 years now. You don’t have to wait for the next release (like EF) – you can use it *now*.
  • Open source is not always an option (depending on your environment). LINQ to SQL is good to go here.
  • The skills you learn in LINQ to SQL are transferrable.  In other words, if you learn LINQ to SQL now and later decide to switch to EF next year, you won’t be starting from scratch. Your knowledge will be transferrable.
  • There are also some cool OSS projects for LINQ to SQL such as Fluent LINQ to SQL.

And finally, LINQ to SQL is just flat out *good*. While it may not be perfect (no framework is) the designers of LINQ to SQL inside Microsoft really got far more right than wrong when creating LINQ to SQL. You can use it with a RAD designer or you can hand code all your classes.  You can use it with C# attributes for mapping or external XML mapping files (or fluent mapping with OSS libraries). You can use it with auto-generated SQL or stored procedures. You can use it with POCO classes. You can use it in an N-Tier application without having to worry about serialization of your entities. It supports lazy loading or eager loading. The list goes on.

Having implemented numerous production applications with LINQ to SQL, I’m happy with it. But I’ll continue to learn more about it and other data access technologies as well as they come out.

If you’re in Rockville tomorrow night and have a desire to start learning LINQ to SQL, come on out!


Saturday, November 07, 2009 #

In an effort to continually improve as a developer, one of the things I do is read lots of books. Recently I read ASP.NET MVC in Action by Jeffrey Palermo, Ben Scheirman, and Jimmy Bogard. In short, I consider this a “must read” for anyone who is serious about developing with the ASP.NET MVC framework.

I’ve heard some people say that this should not be your first MVC book because it is more advanced than other MVC books available.  While I can understand that logic to a degree, I think it would be more accurate to say that if you’re literally brand new to MVC, this might not be the best “introductory” book.  However, if I could only own one book on MVC, this book would be it. There are two common themes from this book that I really enjoyed. First, the authors base their content on “real world” concepts rather than just explaining every topic in a mechanical way. This gives a great real world context throughout the book.  Secondly, the authors are not afraid to be “opinionated” in their recommended best practices for the MVC framework. These are aspects that are lacking in many technical books.

The book starts out with a nice introduction to MVC (and it’s not too advanced to follow in the least). One of the things I really liked about this first chapter is that it spent some time discussing the history of web development which gave great context to where and how ASP.NET MVC fits into the discussion. This included many of the reasons as to *why* we have the MVC framework to begin with. The very next chapter dives into the Model of MVC and does a great job explaining the differences between domain models and presentation or view models.  Philosophically, I really agree with their concepts around view models and I have referenced some of them before on this blog. Understanding these view model concepts is essential to building mature MVC applications.

The books then dives into Controllers. The aspect I enjoyed most about this was the emphasis on unit testing. This included mocking and best practices for dependencies. The Controllers chapter ended with a discussion of action filters which was decent but I would have liked if the discussion of action filters had been expanded a little. The Views chapter provided great content covering validation, custom html helpers, partial views, and more. I didn’t find the Views chapter to be very advanced at all – rather, it provided a solid foundation for the type of information developers should know when building views.

I really appreciated the chapter on Routing. It discussed designing the routing topology of your application up front which is often overlooked. It also discussed REST best practices. The examples of Routing constraints were one of the strongest parts of the chapter and they are an area that I’ve observed is often overlooked in MVC applications. My favorite part of the Routing chapter was unit testing routes with the very cool route testing extensions available in the MvcContrib project which makes unit testing routes trivial. For example, it showed how you can test a route in one simple line of code like this: "~/boiseCodeCamp/edit".ShouldMapTo<ConferenceController>(x => x.Edit("boiseCodeCamp"));

Towards the end of the book there was a chapter dedicated to exploring (for the sake of contrasting and understanding historical context) MonoRail and Ruby of Rails.  I always find the comparisons between Ruby on Rails and MVC very interesting and that was true in this book as well.  However, I didn’t find myself as engaged in the MonoRail discussion and I didn’t think it added as much to the book as the Ruby on Rails section.

Probably the best chapter in the book was the one dedicated to Best Practices. Once again the authors were not afraid to be opinionated in their recommendations and this was based on “real world” experience with the framework (for which there is no substitute). One example I really liked from this section was the advocating of the RenderAction() method. This method has not been without its share of controversy because there are some “purists” that believe the existence of this method violates the tenets of the MVC framework because this means the view has some “knowledge” of the controllers. However, the authors point out (correctly, in my opinion) that the method allows for a much more elegant implementation in many cases that is a very pragmatic choice that actually leads to *better* separation of concerns in many instances since the partial gets its own controller.

Learning the mechanics of MVC is important. But even more important is learning best practices and how you can extend the MVC framework to suit your needs when the situation requires it. In my opinion, this is the best book I’ve read that can help get you to that goal.


Thanks to everyone who attended my “MVC in the Real World” presentation at CMAP Code Camp today.  The code as well as the PowerPoint can be downloaded here:

MVC in the Real World Download

I also had a few other requests during the talk.  First, I had a request to post the code as it looked at the very beginning of my talk before I modified anything.  You’ll find that link on the download page above as well (file name: PersonalInfoManager-ReadlWorldMVC-Begin.zip). 

Second, I was asked about a couple of the tools I was using.  You can see the links for all the tools I use (almost all free) on my Developer Tools and Utilities page.

Third, I had a request to post some links that discussed some of the Unit Testing best practices. Brad Wilson (one of the primary developers of xUnit) co-authored this excellent article: Effective Unit Testing. I also really like this slide deck which he also published: Lessons Learned in Programmer Testing. Roy Osherove also has a great post on Naming Standards for Unit Tests. Finally, I love this article by Jeremy Miller in MSDN magazine entitled Designing for Testability. One of his article’s major premises is that “testable” code typically will naturally result in “well designed” code – a concept that I’m a huge fan of.


Wednesday, November 04, 2009 #

Thanks to everyone who attended my C# 4.0 New Languages Features presentation at CMAP last night.  Both the code and PowerPoint are available for download.

C# 4.0 New Language Features Download

After the presentation, I had a few people ask me about some of tools I was using.  They can all be found on my Developer Tools and Utilities page. To create my snippets, I’ve been using a tool called Snippy for years (link included on Developer Tools page).  However, lately I’ve also been using Snippet Designer which is a Visual Studio add-in that is also quite good.


Sunday, November 01, 2009 #

I’ll be giving a presentation on C# 4.0 New Language Features this Tuesday at the CMAP Main Meeting.

Also I’ll be presenting MVC in the Real World this Saturday at CMAP Code Camp.

Hope to see you there!


Sunday, October 25, 2009 #

Since MVC has been released I have observed much confusion about how best to construct view models. Sometimes this confusion is not without good reason since there does not seem to be a ton of information out there on best practice recommendations.  Additionally, there is not a “one size fits all” solution that acts as the silver bullet. In this post, I’ll describe a few of the main patterns that have emerged and the pros/cons of each. It is important to note that many of these patterns have emerged from people solving real-world issues.

Another key point to recognize is that the question of how best to construct view models is *not* unique to the MVC framework.  The fact is that even in traditional ASP.NET web forms you have the same issues.  The difference is that historically developers haven’t always dealt with it directly in web forms – instead what often happens is that the code-behind files end up as monolithic dumping grounds for code that has no separation of concerns whatsoever and is wiring up view models, performing presentation logic, performing business logic, data access code, and who knows what else.  MVC at least facilitates the developer taking a closer look at how to more elegantly implement Separation of Concerns.

Pattern 1 – Domain model object used directly as the view model

Consider a domain model that looks like this:

   1:  public class Motorcycle
   2:  {
   3:      public string Make { get; set; }
   4:      public string Model { get; set; }
   5:      public int Year { get; set; }
   6:      public string VIN { get; set; }
   7:  }

When we pass this into the view, it of course allows us to write simple HTML helpers in the style of our choosing:

   1:  <%=Html.TextBox("Make") %>
   2:  <%=Html.TextBoxFor(m => m.Make) %>

And of course with default model binding we are able to pass that back to the controller when the form is posted:

   1:  public ActionResult Save(Motorcycle motorcycle)

While this first pattern is simple and clean and elegant, it breaks down fairly quickly for anything but the most trivial views. We are binding directly to our domain model in this instance – this often is not sufficient for fully displaying a view.

Pattern 2 – Dedicated view model that *contains* the domain model object

Staying with the Motorcycle example above, a much more real-world example is that our view needs more than just a Motorcycle object to display properly.  For example, the Make and Model will probably be populated from drop down lists. Therefore, a common pattern is to introduce a view model that acts as a container for all objects that our view requires in order to render properly:

   1:  public class MotorcycleViewModel
   2:  {
   3:      public Motorcycle Motorcycle { get; set; }
   4:      public SelectList MakeList { get; set; }
   5:      public SelectList ModelList { get; set; }
   6:  }

In this instance, the controller is typically responsible for making sure MotorcycleViewModel is correctly populated from the appropriate data in the repositories (e.g., getting the Motorcycle from the database, getting the collections of Makes/Models from the database).  Our Html Helpers change slightly because they refer to Motorcycle.Make rather than Make directly:

   1:  <%=Html.DropDownListFor(m => m.Motorcycle.Make, Model.MakeList) %>

When the form is posted, we are still able to have a strongly-typed Save() method:

   1:  public ActionResult Save([Bind(Prefix = "Motorcycle")]Motorcycle motorcycle)

Note that in this instance we had to use the Bind attribute designating “Motorcycle” as the prefix to the HTML elements we were interested in (i.e., the ones that made up the Motorcycle object).

This pattern is simple and elegant and appropriate in many situations. However, as views become more complicated, it also starts to break down since there is often an impedance mismatch between domain model objects and view model objects.

 

Pattern 3 – Dedicated view model that contains a custom view model entity

As views get more complicated it is often difficult to keep the domain model object in sync with concerns of the views.  In keeping with the example above, suppose we had requirements where we need to present the user a checkbox at the end of the screen if they want to add another motorcycle.  When the form is posted, the controller needs to make a determination based on this value to determine which view to show next. The last thing we want to do is to add this property to our domain model since this is strictly a presentation concern. Instead we can create a custom “view model entity” instead of passing the actual Motorcycle domain model object into the view. We’ll call it MotorcycleData:

   1:  public class MotorcycleData
   2:  {
   3:      public string Make { get; set; }
   4:      public string Model { get; set; }
   5:      public int Year { get; set; }
   6:      public string VIN { get; set; }
   7:      public bool AddAdditionalCycle { get; set; }
   8:  }

This pattern requires more work and it also requires a “mapping” translation layer to map back and forth between the Motorcycle and MotorcycleData objects but it is often well worth the effort as views get more complex.  This pattern is strongly advocated by the authors of MVC in Action (a book a highly recommend).  These ideas are further expanded in a post by Jimmy Bogard (one of the co-authors) in his post How we do MVC – View Models. I strongly recommended reading Bogard’s post (there are many interesting comments on that post as well). In it he discusses approaches to handling this pattern including using MVC Action filters and AutoMapper (I also recommend checking out AutoMapper).

Let’s continue to build out this pattern without the use of Action filters as an alternative. In real-world scenarios, these view models can get complex fast.  Not only do we need to map the data from Motorcycle to MotorcycleData, but we also might have numerous collections that need to be populated for dropdown lists, etc.  If we put all of this code in the controller, then the controller will quickly end up with a lot of code dedicated just to building the view model which is not desirable as we want to keep our controllers thin. Therefore, we can introduce a “builder” class that is concerned with building the view model.

   1:  public class MotorcycleViewModelBuilder
   2:  {
   3:      private IMotorcycleRepository motorcycleRepository;
   4:   
   5:      public MotorcycleViewModelBuilder(IMotorcycleRepository repository)
   6:      {
   7:          this.motorcycleRepository = repository;
   8:      }
   9:   
  10:      public MotorcycleViewModel Build()
  11:      {
  12:          // code here to fully build the view model 
  13:          // with methods in the repository
  14:      }
  15:  }

This allows our controller code to look something like this:

   1:  public ActionResult Edit(int id)
   2:  {
   3:      var viewModelBuilder = new MotorcycleViewModelBuilder(this.motorcycleRepository);
   4:      var motorcycleViewModel = viewModelBuilder.Build();
   5:      return this.View();
   6:  }

Our views can look pretty much the same as pattern #2 but now we have the comfort of knowing that we’re only passing in the data to the view that we need – no more, no less.  When the form is posted back, our controller’s Save() method can now look something like this:

   1:  public ActionResult Save([Bind(Prefix = "Motorcycle")]MotorcycleData motorcycleData)
   2:  {
   3:      var mapper = new MotorcycleMapper(motorcycleData);
   4:      Motorcycle motorcycle = mapper.Map();
   5:      this.motorcycleRepository.Save(motorcycle);
   6:      return this.RedirectToAction("Index");
   7:  }

Conceptually, this implementation is very similar to Bogard’s post but without the AutoMap attribute.  The AutoMap attribute allows us to keep some of this code out of the controller which can be quite nice.  One advantage to not using it is that the code inside the controller class is more obvious and explicit.  Additionally, our builder and mapper classes might need to build the objects from multiple sources and repositories. Internally in our mapper classes, you can still make great use of tools like AutoMapper.

In many complex real-world cases, some variation of pattern #3 is the best choice as it affords the most flexibility to the developer.

 

Considerations

How do you determine the best approach to take?  Here are some considerations to keep in mind:

Code Re-use – Certainly patterns #1 and #2 lend themselves best to code re-use as you are binding your views directly to your domain model objects. This leads to increased code brevity as mapping layers are not required. However, if your view concerns differ from your domain model (which they often will) options #1 and #2 begin to break down.

Impedance mismatch – Often there is an impedance mismatch between your domain model and the concerns of your view.  In these cases, option #3 gives the most flexibility.

Mapping Layer – If custom view entities are used as in option #3, you must ensure you establish a pattern for a mapping layer. Although this means more code that must be written, it gives the most flexibility and there are libraries available such as AutoMapper that make this easier to implement.

Validation – Although there are many ways to perform validation, one of the most common is to use libraries like Data Annotations. Although typical validations (e.g., required fields, etc.) will probably be the same between your domain models and your views, not all validation will always match.  Additionally, you may not always be in control of your domain models (e.g., in some enterprises the domain models are exposed via services that UI developers simply consume).  So there is a limit to how you can associate validations with those classes.  Yes, you can use a separate “meta data” class to designate validations but this duplicates some code similar to how a view model entity from option #3 would anyway. Therefore, option #3 gives you the absolute most control over UI validation.

 

Conclusion

The following has been a summary of several of the patterns that have emerged in dealing with view models. Although these have all been in the context of ASP.NET MVC, the problem with how best to deal with view models is also an issue with other frameworks like web forms as well. If you are able to bind directly to domain model in simple cases, that is the simplest and easiest solution. However, as your complexity grows, having distinct view models gives you the most overall flexibility.


Thursday, October 22, 2009 #

I ran into a small issue today when using the FluentHtml Select() HtmlHelper.  My original code was not properly setting the value of the selected item in the drop down:

<%=this.Select(m => m.Motorcycle.Make).Selected(Model.Motorcycle.Make).Label("Vehicle Make").Options(Model.MakeList)%>

I kept ending up with no item being selected from the drop down even though I definitely had a vehicle Make populated in my model and my drop down was correctly populated with the collection from the “MakeList” property of the view model.  It turns out that the solution was a simple matter of corrected ordering:

<%=this.Select(m => m.Motorcycle.Make).Options(Model.MakeList).Selected(Model.Motorcycle.Make).Label("Vehicle Make")%>

In hindsight I guess this order makes a little more sense intuitively anyway.  However, the fluent API did not constrain me from running into this issue.  So, just a heads up, when using the Select() helper, set the Options() first, and then set the selected value by invoking the Selected() helper method.


Wednesday, October 14, 2009 #

I ran into an interesting IoC issue today that was ultimately resolved by some extremely helpful email assistance by Chad Myers. I’ll post the solution here in the hopes that someone else will find it helpful. Here is the code to set up the example:

   1:  public interface IFoo
   2:  {
   3:      IBar Bar { get; set; }
   4:  }
   5:   
   6:  public class Foo : IFoo
   7:  {
   8:      public IBar Bar { get; set; }
   9:   
  10:      public Foo(IBar bar)
  11:      {
  12:          this.Bar = bar;
  13:      }
  14:  }
  15:   
  16:  public interface IBar
  17:  {
  18:      bool Flag { get; set; }
  19:  }
  20:   
  21:  public class Bar : IBar
  22:  {
  23:      public bool Flag { get; set; }
  24:   
  25:      public Bar(bool flag)
  26:      {
  27:          this.Flag = flag;
  28:      }
  29:  }

The key here is that Bar has a constructor that takes a Boolean parameter and there are some circumstances where I want Bar to have a true parameters and some instances where I want it to be false.  Because of this variability, I can’t just initialize like this:

   1:  x.ForRequestedType<IBar>().TheDefault.Is.OfConcreteType<Bar>().WithCtorArg("flag").EqualTo(true);

That won’t work because that only supports the “true” parameter for IBar. In order to support both, I need to utilize named instances.  Therefore, my complete StructureMapBootstrapper looks like this:

   1:  public static class StructureMapBootstrapper
   2:  {
   3:      public static void Initialize()
   4:      {
   5:          ObjectFactory.Initialize(x =>
   6:              {
   7:                  x.ForRequestedType<IFoo>().TheDefaultIsConcreteType<Foo>();
   8:                  x.ForRequestedType<IBar>().TheDefault.Is.OfConcreteType<Bar>().WithCtorArg("flag").EqualTo(true).WithName("TrueBar");
   9:                  x.ForRequestedType<IBar>().TheDefault.Is.OfConcreteType<Bar>().WithCtorArg("flag").EqualTo(false).WithName("FalseBar");
  10:              });
  11:      }
  12:  }

This now enables me to create instances of IBar by using the GetNamedInstance() method.  However, the primary issue is that I need to create an instance of IFoo and Foo has a nested dependency on IBar (where the parameter can vary).  It turns out the missing piece to the puzzle is to simply leverage the ObjectFactory’s With() method (in conjunction with the GetNamedInstance() method) which takes an object instance and returns an ExplicitArgsExpression to enable the fluent syntax. Therefore, these instances can easily be instantiated either way like this:

   1:  var fooWithTrueBar = ObjectFactory.With(ObjectFactory.GetNamedInstance<IBar>("TrueBar")).GetInstance<IFoo>();
   2:  var fooWithFalseBar = ObjectFactory.With(ObjectFactory.GetNamedInstance<IBar>("FalseBar")).GetInstance<IFoo>();

Just another example of how IoC containers can enable us to keep clean separation of concerns in our classes and enable us to avoid cluttering our code with the wiring up of dependencies.


I often get asked what IoC Container I prefer.  Short answer: StructureMap. I love the fluent syntax for configuration. Overall, it’s easy to use, has many advanced features, and is very lightweight.  I view the learning curve with StructureMap as relatively small.  It is one of the longest-lived IoC containers (if not *the* longest) and has a huge adoption rate which means it’s quite mature and not difficult to find code examples online. For example, there is the StructureMap mailing list. Additionally, the community is very proactive – I just sent an email question to Chad Myers today and got a response within minutes that solved my issue. The creator of StructureMap, Jeremy Miller, has one of the most useful blogs around (in addition to his column in MSDN magazine).

Despite all this, there are still several other very high quality IoC containers available including: Unity, Ninject, Windsor, Spring.NET, and AutoFac. Unity is Microsoft’s offering in the IoC space and often it gets picked simply because it’s got the “magical” Microsoft label on it.  In fact, some organizations (for better or worse – usually worse) have policies *against* using OSS software and your only choice is to look at the offerings on the Microsoft platform.  Despite this, Unity is actually pretty good but by P&P’s own admission, there are instances where StuctureMap implementation is a little more elegant than Unity. But Unity does still have some compelling reasons to use it. In fact, if you are already using the Microsoft Enterprise Library Application Blocks, choosing Unity makes sense for a little more seamless experience.

Having said all this, there is one other major caveat to my preference towards StructureMap – it’s the IoC tool I’m most familiar with. Therefore you should take a recommendation from me (or *anyone*) with a grain of salt.  Ultimately the features of the various IoC’s are going to be comparable and it’s the developer familiarity with that tool that is going to make the difference.  For folks new to IoC, most of the uses are going to be for simple constructor dependency injection and all the IoC frameworks can handle that easily.  Given the wealth of quality IoC frameworks, we need another IoC framework about as bad as we need another data access technology. :)


Saturday, October 10, 2009 #

Thanks to everyone who attended my session today at NoVa Code Camp.  Both the code and PowerPoint slides are available for download.

Download samples for: MVC in the Real World. Check out the readme.txt file in Solution Items and all SQL scripts for creating the databases.


Wednesday, October 07, 2009 #

This Saturday (October 10) I’ll be presenting at the NoVa Code CampRegistration is still open.

I will be presenting “MVC in the Real World”.  There are many great sessions on the schedule.  Hope to see you there!


Sunday, October 04, 2009 #

Thanks to everyone who attended my sessions yesterday at Richmond Code Camp.  Both the code and PowerPoint slides are available for download.

Download samples for: MVC in the Real World. Check out the readme.txt file in Solution Items and all SQL scripts for creating the databases.

Download samples for: C# 4.0 New Language Features.

I had several questions about some of the tools I was using during the presentations (all of which are free).  For the zooming and highlighting, I was using a tool called ZoomIt. For the code snippets, I was just utilizing the built-in code snippets functionality of Visual Studio – however, I use a tool called Snippy to create all of my custom snippets. You can find links to those tools and many other tools I use on my Developer Tools and Utilities post.