Sir Thomas - 365 - Jan 7, 2015

Would there be a savings in overhead if Services could be auto-registered as Reuse.Container instead of None?  

I have several services that in-turn call other services to generate its response (eg: CarStatusService calls WheelService, EngineService, RadioService, etc.)  If the CarStatusService was being called at very high frequency, each time CarStatusService is called it will ResolveService<…> which in-turn creates new instances each time.

How to have the services automatically register, but set as singleton reuse in the container?  This way, each time CarStatusService is requested, its ResolveService<…> calls can re-use the same instance.  If the service is called thousands of time, say every 100ms by several clients, then any time savings will compound.

Is this something that can be post-processed after the AppHost configure?  Or am I barking up the wrong tree.

The default lifecycle is to re-use the same singleton instance, you would need to explicitly register the dep with Reuse.None in order to force creating a new instance each time.

Sir Thomas:

My understanding was that auto-registered services are set to Reuse.None and that a new instance is created on each ResolveService.

http://stackoverflow.com/questions/24481853/servicestack-service-being-singleton-by-default-may-cause-its-request-context-to

The default lifecycle for your dependencies is singleton scope. Services are always executed in a new instance and disposed of after each request.

Matt Cowan:

I’ve faced this on several projects, and personally, I’ve preferred to thin out the service methods to use intermediate objects to coordinate the work, instead of calling ResolveService everywhere. Thin out the service layers a little and abstract the ‘work’ inside those services into their own objects that can be re-used across services, and give those worker/dispatch/adapter objects whatever lifetime scope they need, maybe even pass the IRequest or IDbConnection as a method parameter as needed (and you can make the methods async too, or accept lambdas for downstream activity), and still take advantage of the built-in dispose functionality.

Sir Thomas:

Thanks Matt, interesting idea that can work in some of my cases.  For now I am experimenting with a customized Resolve method that can optionally looked for a named instance and dynamically add them to the container.  Haven’t yet tested it under load though.