c# - When should I use dependency injectors like Ninject -
problem
i have problems understand when , in code should use dependency injectors ninject.
code
let's example have following code:
//without ninject: imailsender mailsender = new mockmailsender(); //with ninject: imailsender mailsender = kernel.get<imailsender>();
this 1 not dependency injection make sense use ninject in scenario?
another example shows how code gets messed using dependency injector:
public void calculaterevenuerecognitions(icontract contract) { //with ninject var kernel = new standardkernel(new defaultmodule()); var arguments = new list<iparameter> { new constructorargument("amount",contract.revenue), new constructorargument("date", contract.whensigned) }; contract.addrevenuerecognition(kernel.get<irevenuerecognition>(arguments.toarray())); //without ninject: contract.addrevenuerecognition(new revenuerecognition(contract.revenue, contract.whensigned)))); }
question
when should use dependency injector?
- on constructor injections, parameter injection, etc.
- on object creation (do dependency injectors replace classical object creation new?)
- are others?
when shouldn't use dependency injectors?
the basic premise not rely on concrete classes (like said newing concrete classes) , inject implementations (via interfaces). depends on specific task you're performing , under conditions (windows service, wcf service, asp.net), in instances have interface methods wish expose publicly, so
public interface ibar { void dostuff(); }
then bind these specific class using ninject i.e.
bind<ibar>().to<barclass>();
so @ startup ninject goes , gets configured implementation. plus side implementation configured, it's easy swap implementation long it's implementing interface. if had class wanted use instead of barclass, rebind i.e.
bind<ibar>().to<newbarclass>();
so wherever need use newbarclass, you'd pass in this
public class userofnewbarclass { public userofnewbarclass(ibar newbarclass) { } // use ibar interface }
also, can mock out interfaces when testing means can isolate single concrete classes , test them in complete isolation. can more complex things, can learn later binding based off property values , conditional binding on you're injecting into.
for entry points consult these
wcf - http://www.aaronstannard.com/post/2011/08/16/dependency-injection-ninject-wcf-service.aspx
mvc - http://www.shahnawazk.com/2010/12/dependency-injection-in-aspnet-mvc-3.html
windows service - using ninject windows service
it's quite hard understand @ first container (in case ninject) figures out implementation inject based off binding specify . end goal inject class needs in order perform it's methods can test in isolation (it helps keep class clean , uncluttered). preferred way injection via constructor class have of dependencies when it's created. property injection of course doable properties, can't guarantee have been set.
Comments
Post a Comment