IOC dispose question

Let’s say I have some dependencies registered in a container.

container.AddSingleton<IMySingleton, MySingleton>();
container.AddTransient<IMyTransient, MyTransient>();

and let’s say that MySingleton and MyTransient are both IDisposable

ServiceStack should do the right thing for me at either the end of the HTTP Request, or at the end of the service lifetime and dispose the registered instances. All good there.

Now, if somewhere in the service, or filters, or elsewhere I do something like:

var instance = IRequest.Resolve<IMySingleton>();

OR perhaps in my AppHost:

var instance = container.Resolve<IMySingleton>();

Then I understand that I am responsible for calling Dispose(); in the returned instance.
Isn’t that correct?

If so, then what actually happens if I call instance.Dispose() on the IMySingleton instance? Does that mean that the singleton itself will be disposed, and will be disposed if it is injected elsewhere by ServiceStack?

Seems like I will need to know if it is a singleton or transient to know whether to dispose the instance or not. And not dispose the singleton that are already registered in the container. Is that correct?

How do I tell if it is registered as a singleton or as a transient in the container?

Right you will need to dispose all IDisposable dependencies you’ve resolved yourself and not dispose singleton dependencies.

Cool, thanks for that confirmation.

Is there a way to tell if a dependency is registered in the container as a singleton, or as a transient?

There’s no IOC API for it, but your App should know as it registered it. If you want you can inherit a custom ISingleton marker interface, but I’d personally drop the IDisposable interface on singletons and if it needs to be Disposed when the AppHost is disposed add it in OnDisposeCallbacks.

Yeah, the code that needs to know this does not have the knowledge of the App. Its library code.
I like the marker interface idea. Might also need to use reflection on the container, as the data is in there.
Just need to think it through.

Is there any chance we could get a method on Container like:

GetReuseScope<TService>(), to tell us what the ReuseScope of the registration is for a given type?

Perhaps under the covers, all that method does is return the ServiceEntry from a call to GetEntry just like Container.Exists<TService>() does?

Adding a dependency to a concrete IOC in your library code isn’t an approach I’d consider but I’ve added a GetServiceEntry<T> in this commit so you can access the IOC registration entry.

Thanks, that’s great.
Could I please push for an overload that takes the named registration for both GetServiceEntryNamed<TService>(string name) and ExistsNamed<TService>(string name) method too?

Can you send PR’s for additional APIs you need please, I can evaluate them there.

1 Like