Disposable singleton in C#

前端 未结 8 1837
Happy的楠姐
Happy的楠姐 2020-12-05 08:14

I have a singleton that uses the \"static readonly T Instance = new T();\" pattern. However, I ran into a case where T is disposable, and actually needs to be disposed for u

8条回答
  •  醉酒成梦
    2020-12-05 09:12

    At that point I don't think I'd really consider it to be a singleton any more, to be honest.

    In particular, if a client uses a singleton they're really not going to expect that they have to dispose of it, and they'd be surprised if someone else did.

    What's your production code going to do?

    EDIT: If you really, really need this for unit tests and only for unit tests (which sounds questionable in terms of design, to be frank) then you could always fiddle with the field using reflection. It would be nicer to work out whether it should really be a singleton or whether it should really be disposable though - the two very rarely go together.

提交回复
热议问题