c# - Dependency injection in long-running Windows service - Composition root the right idea? -
i writing windows service (if goes according plan) run months @ time. throughout lifetime of service, maintain several wcf services (named pipes communicating other local apps), run embedded data store (ravendb probably, more or less irrelevant question), , use third-party software maintain sip service (voip functionality). of challenges facing means having react events , create new business objects handle these events represent.
now, i've read mark seemann's book (at least relevant parts discussion), , understand why service locator bad, , why handling in composition root (service starting point in case) - in general case.
however, don't understand how can apply every situation. see how perfect in cases can compose whole root @ start of application, or in mvc ioc engine used per request framework. however, long-running service, imagine inefficient in best case, , impossible in cases, create objects front. can't imagine being able write non-trivial service gets objects ever need front, , never need create new ones life goes on.
now, isn't enough lure me dark side , take on expense of hidden dependencies service locator have me do. right thing here? if have callhandlerservice needs created in response each incoming call (because uses expensive, unmanaged resources instance), how go doing that?
composition root + wee bit of service locator?
that last part wasn't serious, still love know how solve properly.
it possible break question two:
- how manage scope
- avoid creation of possible dependencies up-front
- create only required dependencies
- how manage lifetime
- keep references created dependencies
- reuse dependencies if possible
- cleanup them possible
how manage scope
you define either interfaces or realizations of several specialized abstract factories, each of them limited manage only own special sort of dependencies. example: 1 database related dependencies, sip related. inject factories themselves, not dependencies, , retrieve dependencies them.
isn't sound service locator? yes is, not service locator. read more on @ mark seemann blog: abstract factory or service locator?.
and if abstract factories ok, take @ ninject.extensions.factory create them automatically based upon ikernel
configuration
how manage lifetime
if going run service 24-7, more complex , important part. here give several practical advises:
- for such kind of services, failures @ external dependency side (i.e. database, services) are routine, not exception
- do not keep references dependencies in code aiming performance or reuse
- do not use complex lifetimes (for example named scope ninject )
- do release dependencies possible. configure ninject manage them you.
- think timeouts dependencies, recreate new instances
- may long-running tasks, create separate instance of
kernel
, , make sure have disposed them afterwards
Comments
Post a Comment