在C#中一次性单 [英] Disposable singleton in C#

查看:131
本文介绍了在C#中一次性单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用一个单身静态只读牛逼实例=新T();模式。但是,我碰到了,其中T是一次性的,需要实际处理单元测试的情况。我如何可以修改这个模式支持一次性单

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 unit tests. How can I modify this pattern to support a disposable singleton?

我想该接口是一样的东西:

The interface I would like is something like:

var x = Foo.Instance;
var y = Foo.Instance; // x == y
...
x.Release(); // this causes the next Foo.Instance to return a fresh object
             // also, it assumes no further operations on x/y will be performed.

请注意 - 该模式必须是线程安全的,当然

Note - the pattern has to be thread-safe, of course.

修改 - 为生产代码的目的,这是一个真正的单身。问题是,它锁定了一些文件,所以在单元测试中清理,我们必须处理它。

Edit - for the purpose of production code, this is a true singleton. The thing is that it locks some files, and so for cleanup in unit tests we have to dispose it.

我也喜欢,可重用的模式,如果可能的话

I would also prefer a pattern that can be reused, if possible.

推荐答案

标记发布内部,并使用 InternalsVisibleTo 属性它仅暴露你的单元测试组件。你可以做到这一点,或者如果你在自己的汇编警惕有人会打电话给它,你可以将其标记为私人和访问它使用反射。

Mark Release as internal and use the InternalsVisibleTo attribute to expose it only to your unit testing assembly. You can either do that, or if you're wary someone in your own assembly will call it, you can mark it as private and access it using reflection.

使用在你的单身终结调用的单实例的Dispose 方法。

Use a finalizer in your singleton that calls the Dispose method on the singleton instance.

在生产代码中,只有一个的AppDomain 的卸载将导致处置单例。在测试代​​码,就可以启动对发布自己的电话。

In production code, only the unloading of an AppDomain will cause the disposal of the singleton. In the testing code, you can initiate a call to Release yourself.

这篇关于在C#中一次性单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆