当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Should injected properties be disposed?

问题描述:

Short best practice question: If an object A is injected into another object B, should then object B implement IDisposable and dispose A when B is disposed?

网友答案:

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.

网友答案:

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.

网友答案:

(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 (i.e. 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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: