When using Ninject with ServiceStack, how would I specify that an object’s lifetime is to be per-request, calling any IDisposable.Dispose method if necessary?
Per the docs, the default way of doing this is:
container.RegisterAutoWiredAs<MyType,IMyType>().ReusedWithin(ReuseScope.Request);
However, I have to use the NinjectContainerAdapter for my project. Normally I’d install Ninject.Web.Common and write:
kernel.Bind<IMyType>().To<MyType>().InRequestScope()
and my instance would be disposed of at the end of the request. How would I go about doing this in ServiceStack, say in a self-hosted scenario?
You will have to implement an
INinjectHttpApplicationPluginfor ServiceStack. In the methodobject GetRequestScope(IContext context);you must return some object that has the lifetime of a request (an equivalent toHttpContext.Current))Probably you could add an object to
HostContextand return that one as scope. Best you make that object implementINotifyWhenDisposedand dispose it at the end of the request so that the objects are released imediately after the request instead of waiting for the object to be garbage collected..