c# - Autowiring with Ninject -
i have winforms application i've started using ninject with. majority of tutorials ninject show setup autowiring this:
using (ikernel kernel = new standardkernel()) { kernel.bind<itaxcalculator>() .to<taxcalculator>() .withconstructorargument("rate", .2m); var tc = kernel.get<itaxcalculator>(); assert.equal(20m, tc.calculatetax(100m)); }
that's great if intend on implementing class @ startup short script, i'm not sure how use objects in other classes , libraries in application. curious if ninject can handle dependencies similar spring in this article.
package testbean; import org.springframework.beans.factory.annotation.autowired; import org.springframework.stereotype.service; import writer.iwriter; @service public class myspringbeanwithdependency { private iwriter writer; @autowired public void setwriter(iwriter writer) { this.writer = writer; } public void run() { string s = "this test"; writer.writer(s); } }
you able specify in xml instance inject iwriter. run code needed:
package main; import org.springframework.beans.factory.beanfactory; import org.springframework.context.applicationcontext; import org.springframework.context.support.classpathxmlapplicationcontext; import testbean.myspringbeanwithdependency; public class main { public static void main(string[] args) { applicationcontext context = new classpathxmlapplicationcontext("meta- inf/beans.xml"); beanfactory factory = context; myspringbeanwithdependency test = (myspringbeanwithdependency) factory .getbean("myspringbeanwithdependency"); test.run(); } }
with spring, can create , inject iwriter dependency automatically don't have worry how rest of application. using current ninject tutorials have been unable find way , have resorted storing objects object , calling that, isn't best way it.
i've looked high , low way autowire dependencies ninject haven't found answer particular question. appreciated.
the prefered way constructor injection
public class myspringbeanwithdependency { private iwriter writer; public myspringbeanwithdependency(iwriter writer) { this.writer = writer; } public void run() { string s = "this test"; writer.writer(s); } } kernel.bind<iwriter>().to<somewriter>(); kernel.get<myspringbeanwithdependency>();
instead of 1 one bindings above should use conventions specify bindings https://github.com/ninject/ninject.extensions.conventions/wiki/what-is-configuration-by-convention
and should think in bigger terms , as possible 1 single @ application start.
Comments
Post a Comment