是否可以换一个C#单在接口? [英] Is it possible to wrap a C# singleton in an interface?

查看:116
本文介绍了是否可以换一个C#单在接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在有一个类中,我只有静态成员和常量,但是我想用包裹在接口的单来代替它。

I currently have a class in which I only have static members and constants, however I'd like to replace it with a singleton wrapped in an interface.

不过,我怎么能做到这一点,铭记每一个单身落实我见过有一个静态实例方法,从而打破接口规则?

But how can I do this, bearing in mind that every singleton implementation I've seen has a static Instance method, thus breaking interface rules?

推荐答案

一个解决方案,以考虑(而不是手卷你自己)将充分利用IoC容器如: 团结的。

A solution to consider (rather than hand-rolling your own) would be to leverage an IoC container e.g. Unity.

IoC容器中,普遍支持对接口注册一个实例。这提供了您的单身的行为,解决客户对界面会收到单个实例。

IoC containers commonly support registering an instance against an interface. This provides your singleton behaviour as clients resolving against the interface will receive the single instance.

  //Register instance at some starting point in your application
  container.RegisterInstance<IActiveSessionService>(new ActiveSessionService());

  //This single instance can then be resolved by clients directly, but usually it
  //will be automatically resolved as a dependency when you resolve other types. 
  IActiveSessionService session = container.Resolve<IActiveSessionService>();

您也将获得额外的好处,你可以为它注册容易改变单实施针对一个接口。这可以用于测试对生产是有用的,但也许更如此。真正的单身人士可以在测试环境相当痛苦。

You will also get the added advantage that you can vary the implementation of the singleton easily as it is registered against an interface. This can be useful for production, but perhaps more so for testing. True singletons can be quite painful in test environments.

这篇关于是否可以换一个C#单在接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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