asp.net mvc 4 - How do I inject a dependency into non Controller classes? -
i want setting of application (initialisation). in global.asax.cs
.
i'm going need dependency (perhaps repository) achieve goal.
how inject implementation of ifoorepository
?
public class mvcapplication : httpapplication { private static ifoorepository _foorepository; protected void application_start() { // ... ifoo foo = _foorepository.get(0); foo.dosomething(); } }
i tried failed:
public class repositoriesinstaller : iwindsorinstaller { void iwindsorinstaller.install(castle.windsor.iwindsorcontainer container, castle.microkernel.subsystems.configuration.iconfigurationstore store) { container.addfacility<typedfactoryfacility>(); container.register( component.for<ifoo>() .implementedby<foo>() .lifestyletransient(), component.for<ifoorepository>().asfactory()); container.register(classes.fromthisassembly() .basedon<ifoorepository>() .withservicedefaultinterfaces() .lifestyletransient()); } }
how inject dependencies isn't constructed (a static class)?
i've read through documentation interface-based factories don't understand it.
what facilities? used for?
since mvcapplication
class typically trigger initialization of application , registration of components, can't let di container inject dependencies it. besides that, containers have no built-in support of injecting static dependencies, since in context of dependency injection, usefulness of injecting statics limited.
but solution quite simple: should resolve ifoorepository
container after you're done configuring it.
note though should store ifoorepository
in static field when registered singleton. otherwise (accidentally) promote ifoorepository
singleton, might cause kinds of trouble (such concurrency conflicts, or caching problems).
Comments
Post a Comment