I am detecting memory leaks in a ServiceStack service (over some period of time) of various dependencies that would be autowired in the container.
I understand from the docs that Singleton dependencies would be automatically disposed of when the AppHost dies, which makes sense.
However, its not clear to me when Transient instances would be disposed of, if at all.
Is it safe to assume that the IOC disposes of a previous instance it has injected before it injects a new instance of a Transient dependency?
If not, who’s responsibility is the disposal and where should it be done?
Transient dependencies that implement IDisposable injected in Services are disposed of immediately after the Service is executed.
No it’s not dependent upon existing dependency instances, requests are executed concurrently, there could be multiple instances of the same Service being executed in parallel.
Services executed by ServiceStack are released by ServiceStack, but if you manually resolve a Service itself it should be done with a using so that it’s disposed as well, e.g:
using var service = HostContext.ResolveService<MyService>(Request);
service.Any(new MyRequest { ... });
Does ServiceStack automatically dispose of IDisposable dependencies (ReuseScope == Request), or will I need to do something explicitly to dispose of them?
And then what about dependencies that I manually resolve (request.TryResolve<T>) within PreRequestFilters, GlobalRequestFilters, RequestFilters? Are they all taken care of as well by ServiceStack, regardless of their ReuseScope?
They’re disposed at the end of the request, you can override OnEndRequest() to get a callback when it’s called, calling base.OnEndRequest() will dispose them. But I’d personally never use Request Scoped dependencies myself (mentioned on prev occasions - anything I need to be accessed throughout the request pipeline I put in IRequest.Items).
Resolving non singleton IDisposable dependencies within a worker request will also be disposed but if you’re resolving them in a background thread you’ll need to dispose of them yourself. If you implement the Disposable pattern you can also use them within a using block so they’re disposed of immediately. I prefer to dispose of resources immediately after I’m done with them.