command-line-api icon indicating copy to clipboard operation
command-line-api copied to clipboard

[Docs] Does built-in container handle disposal?

Open lonix1 opened this issue 3 years ago • 4 comments

I'm using the built-in container like so:

invocationContext.BindingContext.AddService(x => new ParentService());
invocationContext.BindingContext.AddService(x => new ChildService(x.GetRequiredService<ParentService>()));
invocationContext.BindingContext.AddService(x => new OtherService());
// etc.

An IoC container typically handles disposal. I looked at BindingContext and didn't see anything to this effect, but maybe I'm looking in the wrong place.

Does this library's container dispose services that implement IDisposable?

lonix1 avatar Sep 13 '22 09:09 lonix1

It's not really a container. It doesn't allow open-ended registration, doesn't handle object instantiation, and doesn't handle disposal.

jonsequitur avatar Sep 13 '22 14:09 jonsequitur

What is "open-ended registration" in this context? Open generic types perhaps?

KalleOlaviNiemitalo avatar Sep 13 '22 14:09 KalleOlaviNiemitalo

Open generics aren't supported and type mappings are exact, i.e. if you only register something as IWidget, you can't resolve Widget. Every type must be registered explicitly. It's really intended, at most, as a pass-through to a real container.

jonsequitur avatar Sep 13 '22 14:09 jonsequitur

If I see "IOC" or "DI" then I automatically assume the above. Other people will also get confused and that will lead to bugs... and unnecessary issues in the repo. :wink:

So at some point this should probably be in the docs:

doesn't allow open generics, doesn't handle object instantiation, and doesn't handle disposal

It might be good to provide guidance for disposal; as above, just to avoid unnecessary issues in the repo. My approach:

  • make services implement IDisposable
  • make the composition root implement IDisposable (the class where I call context.BindingContext.AddService(x => new FooService()), for me that's in Program)
  • in Program.Dispose() I also dispose all disposable services

lonix1 avatar Sep 14 '22 02:09 lonix1