Monday, April 19, 2010

Does C# 4.0 Make Poor Man's Dependency Injection Less Poor?

This post by Jimmy Bogard talks about why Poor Man's Dependency Injection is bad. In that post, Jimmy talks about how Poor Man's DI makes dependencies opaque. With C# 4.0 and optional parameters, you can do Poor Man's DI in a way that makes the dependencies more transparent. Consider the following class:

public class MyClass
{
IDataReader reader;
IMessageSender sender;

public MyClass(IDataReader reader = null,
IMessageSender sender = null)
{
this.reader = reader ?? new DefaultDataReader();
this.sender = sender ?? new DefaultMessageSender();
}
}

Does this approach make Poor Man's DI more palatable or should it still be avoided?

No comments:

Post a Comment