Last week Jimmy Bogard posted why he believed the dependency injection pattern appearing in the NerdDinner application was flawed.  I want to take the opportunity to say the pattern in NerdDinner really isn't that bad and I want to explain why.  Before I go on I will say that I entirely agree with Jimmy's thoughts on the pattern for my own code and you won't find the anti-pattern Jimmy describes in my code.

So why isn't the pattern that bad? I see Dependency Injection as generally having at least two major benefits:

  • Testability
  • Flexibility (most often achieved by using an IoC container)

The pattern under scrutiny in NerdDinner accounts for testability, of which I am a firm believer in, but lacks in flexibility.  If I had to rank the two items above, I would rank testability above flexibility.  Testability is a core tenet on which I stand for with the code I write.

Explain Again Why NerdDinner is "Flawed"

To recap here is the code from Jimmy's post:

   1: public class SearchController : Controller {
   2:  
   3: IDinnerRepository dinnerRepository;
   4:  
   5: //
   6: // Dependency Injection enabled constructors
   7:  
   8: public SearchController()
   9:     : this(new DinnerRepository()) {
  10: }
  11:  
  12: public SearchController(IDinnerRepository repository) {
  13:     dinnerRepository = repository;
  14: }

The first constructor, when called, "news up" a new DinnerRepository() and passes it into another constructor on the same object which is generally considered "poor man's dependency injection".  This pattern is considered bad (this an anti-pattern) because some, of which Jimmy is one, believe you shouldn't "new up" new objects this way, choosing instead to allow a container to inject the primal dependency.  The problem I have with this view is that for many applications a container is overkill.  Many applications will only have one concrete implementation of a class, so in many ways this constructor and the object creation could be seen as providing a sensible default to the application, allowing the consumer to create an instance without worry about what else the object needs.

But You Said You Don't Write Your Code that Way?

Absolutely correct, I don't write my code this way.  Why? I already have a container set up in my application and so to not use it would be foolish.  We also have a complex application/domain, sometimes with multiple concrete implementations of an interface.

I used to write code this way using this pattern. Really. I don't feel ashamed to say so. The reason we adopted the dependency injection (DI) pattern in the application where this overloaded constructor "anti-pattern" was used was because DI allows for testability, and as I have previously mentioned, this "anti-pattern" doesn't stand in the way of testing.

I further believe that most developers must make a certain progression on their own.  We can write and share our experiences but in the end every developer out there must some day be convinced in their own time. \They must come to the conclusion on their own, like I did, that using "poor man's injection" will work for many many scenarios but will get ugly fast in others.

What's Really Wrong with "Poor Man's Dependency Injection"?

For simple applications/domain, typically not much (again, my opinion).  For complex domain the issue you will run into is maintainability/flexibility.  If you get to a complex domain and you use the pattern from NerdDinner you will someday have:

   1: public SearchController(new SearchService(new SearchLogService(new Logger()), new SearchRepository(new SessionBuilder()), new SearchResultFormatter(new FormatProvider())))

Ugly for sure.  This is why it's generally considered an "Anti-Pattern".  However for applications where the controller is the service-layer and controllers therefore use repositories, I would not be too concerned with the use of this pattern.

While Jimmy did a great job fixing the application, you first have to believe the application needed fixing.  Which of course, depends on context.  How big/complex is your application/domain?  Jimmy's application/domain is sufficiently complex as is mine, yours may not be.  For NerdDinner I believe the pattern was a suitable choice.


 
Categories: ASP.NET MVC Framework | IoC

I don't want to be a wet blanket, but someone's got to put a stop to the IoC love fest going on out there.  An Inversion of Control (IoC) container , for those of you were aren't yet familiar, allows you to retrieve instances of objects at runtime.  A relatively common solution to a common problem. In the .NET world there is no lack of choices of IoC containers:

(I won't go fully into IoC, but If you'd like more resource you can read Martin Fowler's article on the subject or post specific questions in the comments or contact me through.  Read on, there is value here in this post for you.)

Let me state clearly now, IoC containers are a means to an end and NOT a feature of your application. The goal is to have loosely coupled applications, IoC containers help get you there, but you can absolutely have a loosely coupled application without an IoC container (see the Gang of Four creational patterns).

Occasionally I'll hear some comment about IoC and how great a certain container is or how an application would be so much better if another, sexier, container was used.  Here are some recent tweets that illustrate:

  • Man i love #StructureMap, always finding new things i can do, and have fun doing them
  • really need to look at structuremap, but we''ve invested a lot into castle with our own facilities/resolvers/etc
  • Ninject is da bomb!
  • Switched from Windsor MicroKernel to Ninject in 10KLOC project in < 1 hour by creating a little proxy. Now to complete the conversion.
  • It is a talk on Castle Windsor so i guess Ninject will not do.
  • Can't imagine why somebody would use Ninject beside the fact that it's PURE AND UTTER AWESOME. Yeah! Ninject FTW.

Some of the statements above are probably innocuous, but some rub me slightly the wrong way.  Specifically the two comments above about switching from one container to another. There are probably times when the choice of one container over another makes sense, but I would bet that these scenarios are the exception and not the rule.

Choosing one container over another won't make your application a success, the architecture, or lack there of, will have far more of a say on your application than will your container choice. As yoda might say, "The container you choose does not a good app make".


 
Categories: IoC | Rant | Tools | Windsor

Windsor will stitch together objects for you at runtime based on what components have been registered.  When you ask for an instance of an object from the Windsor/MicroKernel it will return the object using the constructor it can satisfy.

I ran into a problem the other day when I wanted to create an object that accepted three types, the third was a non-primitive that I didn't control.  Castle's website goes into some detail on this in their documentation on Windsor/MicroKernel:

   1: <configuration>
   2:  
   3:     <components>
   4:         <component id="smtp.sender" 
   5:             service="Namespace.IEmailSender, AssemblyName"
   6:             type="Namespace.SmtpMailSender, AssemblyName">
   7:         
   8:             <parameters>
   9:                 <port>10</port>
  10:                 <host>smtphost</host>
  11:             </parameters>
  12:         
  13:         </component>
  14:     </components>
  15:  
  16: </configuration>

the problem I was running into is what if you have a third parameter, which isn't a primitive?  I have the following signature:

   1: public CommunicationGateway(string host, int port, Encoding encoding)
   2: {
   3:     this.host = host;
   4:     this.port = port;
   5:     this.encoding = encoding;
   6: }

The example above fits quite nicely until I hit the third parameter.  How do I define what that third parameter should be in Windsor given that it's not a class that I control nor a primitive type? This felt like it should be easy, but I could not find the information I needed on the Castle website.  I got some help from Castle committer Dru Sellers.  In the end Dru pointed me to a very simple solution; register the type and pass it in using the service lookup notation, ${}

   1: <component id="CommunicationGateway"
   2:            service="ABCCompany.ICommunicationGateway, ABCCompany"
   3:            type="ABCCompany.CommunicationGateway, ABCCompany">
   4:     <parameters>
   5:         <host>#{Host}</host>
   6:         <port>#{Port}</port>
   7:         <encoding>${Encoding}</encoding>
   8:     </parameters>
   9: </component>
  10:  
  11: <component id="Encoding"
  12:            service="System.Text.Encoding, mscorlib"
  13:            type="System.Text.UTF8Encoding, mscorlib">
  14: </component>

You can see from above that I'm registering a component with the service System.Text.Encoding and supplying UTF8Encoding as the implementation.  Now I can use a strongly-typed System.Text.Encoding object and have it configurable in my Windsor Configuration, much more elegant than using a string (primitive-type) and hoping it works. 

Thanks Dru!


 
Categories: Caslte | IoC | Tips & Tricks