简体   繁体   中英

Should injected properties be disposed?

简短的最佳实践问题:如果一个对象A注入另一个对象B,那么对象B应该实现IDisposable并在B处理时配置A?

If you're referring to the dependency injection pattern, I think it depends on the knowledge in Object B about the implementation of Object A. The reason for doing dependency injection like this is usually because you do not know on beforehand how Object A will be implemented and whether it requires IDisposable. The only thing you know is the interface.

Adding this behavior would result in tighter coupling between the two classes, IMO.

I would generally say no; the nature of dependency injection means that the injected object does not know much about the lifecycle of what it was injected with; to some extent, this is the definition of injection. As such, I do not think the injected object should dispose whatever it was injected with; the injecting code should take the responsibility for knowing the complete lifecycle of all the objects it is injecting, and should be able to properly dispose of them when all operations on them are complete, and not before.

(edit: when answering, it wan't clear to me that the question was about IoC/DI; I'll leave this here for reference, but look first at the accepted answer).

If by "injected" you mean that B assumes ownership of A , then yes; example of this would be things like StreamReader .

If it just uses A for a while (but A continues to live beyond B ) then no.

Some APIs allow you to specify (on the constructor) whether ownership should be assumed (ie whether to clean up the injected object). An example of this would be GZipStream .

I think that would really end up being subjective.

It would all boil down to, Who should control the lifetime of object A?

Say for instance object C and D also have object A injected into them, in that case you wouldn't want object B disposing of object A prematurely.

However, in some cases when you know the lifetime of object A should end with B, it is entirely appropriate to have object B dispose of object A.

My 2p would be to argue that A should not be disposed when B is disposed. The whole idea of dependency injection is that you don't have to worry about the bahaviour and lifecycle of the objects you are receiving, you are just handed them.

Then again you want to ensure the object gets cleaned up as soon as it is it is no longer required. Maybe create a mini event system so that you can notify a it needs to be disposed? I guess it depends on the context really.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM