Dependencyinjection: ServiceProvider.Dispose should not stop if a bad service throws on Dispose

Created on 16 Mar 2017  路  6Comments  路  Source: aspnet/DependencyInjection

Currently if there is one badly implemented service that throws on Dispose, then because there is no try/catch in ServiceProvider.Dispose() when enumerating, the whole Dispose stops and bubbles up.

Ideally Dispose on every service implementation shouldn't throw, but the ServiceProvider could be a little more resilient against this typical issue and try to clean up as much as possible, and then bubble up the exception (or aggregate exception?). Even if being a little careful, it can sometimes be easy to miss these issue when implementing a service, especially since the Dispose order is not necessarily intuitive (see https://github.com/aspnet/DependencyInjection/issues/463).

Thoughts?

Most helpful comment

My gut says that if a service throws during dispose, that all bets are off. How is the application intending to continue after such a failure? (This is assuming it isn't during shutdown, in which case I think none of this matters anyway.)

All 6 comments

We could but you could fix your code to not throw in dispose. I'm not even sure what state the object is in at that point...

https://msdn.microsoft.com/en-us/library/fs2xkftw(v=vs.110).aspx

a Dispose method should be callable multiple times without throwing an exception

Not sure throwing when called once is a valid corner case 馃槈

Yup, I already fixed my code. Still thought that ServiceProvider should be a little bit more resilient since it is meant to glue together completely decoupled object graphs. So one bad apple in a big system shouldn't stop the entire container to stop disposing all the other correctly built services.
Just my 2 cents.

My gut says that if a service throws during dispose, that all bets are off. How is the application intending to continue after such a failure? (This is assuming it isn't during shutdown, in which case I think none of this matters anyway.)

In the case of responsibility - I'd argue that it is not the service providers responsibility to handle faulty dispose logic.

Agreed with @Eilon, closing this one.

Was this page helpful?
0 / 5 - 0 ratings