[英]Getting a singleton instance using SimpleInjector for a class which implements a generic type, not actually returning a singleton
I've been experiencing some strange code-issues, and finally seem to have noticed that what as supposed to be acting as Singleton, is not actually a singleton. 我一直在经历一些奇怪的代码问题,最后似乎已经注意到应该充当Singleton的东西实际上并不是Singleton。 This is a cache-class, so I am ending up having multiple-versions of the same cache.
这是一个缓存类,因此我最终拥有同一缓存的多个版本。 I've written some test-code as per below, and in my eyes this should work.
我已经按照下面的代码编写了一些测试代码,在我看来这应该可行。 Am I doing anything wrong, or have I stumbled upon a bug?
我做错了什么,还是偶然发现了一个错误?
public class GenericClassesNotRegisteredAsSingletonTest
{
public interface ICacheManager<T> { }
public class SettingsData { }
public class SettingsCache : CacheManager<SettingsData> { }
public class CacheManager<T> : ICacheManager<T> { }
[Test]
public void Test()
{
var container = new Container();
var registration = Lifestyle.Singleton
.CreateRegistration(typeof(SettingsCache),
typeof(SettingsCache), container);
container.AddRegistration(
typeof(ICacheManager<SettingsData>), registration);
container.Verify();
var cache1 = container.GetInstance<SettingsCache>();
var cache2 = container.GetInstance<SettingsCache>();
bool sameRef = cache1 == cache2;
Assert.That(sameRef == true);
}
}
You made the following registration: 您进行了以下注册:
_container.AddRegistration(
serviceType: typeof(ICacheManager<SettingsData>),
registration: registration);
And you're doing the following resolve: 您正在执行以下解决方案:
_container.GetInstance<SettingsCache>();
You haven't registered SettingsCache
explicitly, but only ICacheManager<SettingsData>
. 您尚未显式注册
SettingsCache
,但仅注册了ICacheManager<SettingsData>
。 Since SettingsCache
is a concrete class, Simple Injector will resolve it as transient instance for you. 由于
SettingsCache
是一个具体的类,因此Simple Injector会将其解析为您的临时实例。
The solution is to either register SettingsCache
explicitly or resolve ICacheManager<SettingsData>
instead. 解决方案是显式注册
SettingsCache
或解析ICacheManager<SettingsData>
。 You can make a second registration with using the same Registration
instance. 您可以使用相同的
Registration
实例进行第二次注册。 For instance: 例如:
_container.AddRegistration(
serviceType: typeof(SettingsCache),
registration: registration);
The Diagnostic Services will warn you about this this type of misconfiguration . 诊断服务将警告您这种类型的错误配置 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.