Friday, October 7, 2011

My Ninject Alternative

Friday, October 07, 2011 Posted by Andre Broers , , 3 comments
I recently read an article about ninject and how great it is to do dependancy injection but I always did it with some reflection and in my opinion, doing dependancy injection my own way is far more simple.

Let’s explain with some code:

I set the implementation of the interface I want in the web.config:
<appSettings>
  <addkey="WatzdPriceDALCType" value="com.bekijkhet.WatzdPrice.DALC.PGsql.WatzdPriceDALC, WatzdPriceDALCPGsql" />
</appSettings>

Then I use the following code to inject the Data Access Layer I specified in the web.config:
public class WatzdPriceBLL : IWatzdPriceBLL
{
  private IWatzdPriceDALC _DALC;

  public WatzdPriceBLL()
  {
    Type typeWatzdPrice = Type.GetType(ConfigurationManager.AppSettings["WatzdPriceDALCType"].ToString());
    _DALC = (IWatzdPriceDALC)Activator.CreateInstance(typeWatzdPrice);
  }

  public WatzdPriceBLL(IWatzdPriceDALC watzdpriceDALC)
  {
    _DALC = watzdpriceDALC;
  }

  ...
}

This will inject the class from the web.config when the Data Access Layer is created without parameters. For unit testing we can call the constructor with the paramter to inject our mock object.

3 comments: