Dependency Injection and Concrete Instance

May 22, 2008 at 6:02 AM
Hi All

Why I found that under some of the example, the object is defined as concrete but not the interface?

Example :-
public class MyObject
{
  private SomeOtherObject _dependentObject;

  [Dependency]
  public SomeOtherObject DependentObject 
  {
    get { return _dependentObject; }
    set { _dependentObject = value; }
  }
} 









I feel it maybe better :-



public class MyObject
{
  private ISomeOtherObject _dependentObject;

  [Dependency]
  public ISomeOtherObject DependentObject
  {
    get { return _dependentObject; }
    set { _dependentObject = value; }
  }
}

Any reason behind?
May 22, 2008 at 4:14 PM
It depends on if you want any implementation of the interface or a specific implementation.  Either will work. 
One other thing, we added Type Mapping to the Composition Container fairly late, so in early work, there was no way for the container to determine which concrete type to inject for a given interface.  With the addition of type mapping support, we should have fixed everything to use interfaces where appropriate.

Sorry about the confusion,
Michael Puleio - patterns & practices
Blog - http://blogs.msdn.com/mpuleio
May 22, 2008 at 5:58 PM
Methinks Michael got a little confused about which forum he was posting in. ;-)

Concrete class vs. interface is a long standing battle over which many a PhD has been granted. There is no one best answer. Concrete classes are more convenient, and arguably make the examples smaller. Interfaces are much more flexible. Abstract base classes give you the best and worst of both models. Evaluate them as they fit for your project.

-Chris
May 22, 2008 at 9:23 PM
Ooooops. 
Chris is right.  I opened a few tabs in my browser with posts to reply to (for projects I run or watch) and lost track of the parent forum for this one.  My above post applies to WCSF (codeplex.com/websf) ONLY. 
Chris, feel free to delete it, if you want.
Sorry about any confusion.
May 23, 2008 at 3:06 AM
Thanks both Chris and Michael.

BTW, If I want a pluggable approach under MVC? Is that means I need to use interface rather than concrete class?