在我的应用程序中,有一组数据提供者和Redis缓存。 每个执行不同的供应商使用,但他们都储存自己的数据在Redis的:没有实例创建的自我注册类
hset ProviderOne Data "..."
hset ProviderTwo Data "..."
我想有一个方法,将删除数据中存在的所有代码提供商。
del ProviderOne
del ProviderTwo
我已经做下面的代码:
void Main()
{
// Both providers have static field Hash with default value.
// I expected that static fields should be initialized when application starts,
// then initialization will call CacheRepository.Register<T>() method
// and all classes will register them self in CacheRepository.RegisteredHashes.
// But code start working only when i created this classes (at least once)
// new ProviderOne();
// new ProviderTwo();
CacheRepository.Reset();
}
public abstract class AbstractProvider
{
//...
}
public class ProviderOne : AbstractProvider
{
public static readonly string Hash =
CacheRepository.Register<ProviderOne>();
//...
}
public class ProviderTwo : AbstractProvider
{
public static readonly string Hash =
CacheRepository.Register<ProviderTwo>();
//...
}
public class CacheRepository
{
protected static Lazy<CacheRepository> LazyInstance = new Lazy<CacheRepository>();
public static CacheRepository Instance
{
get { return LazyInstance.Value; }
}
public ConcurrentBag<string> RegisteredHashes = new ConcurrentBag<string>();
public static string Register<T>()
{
string hash = typeof(T).Name;
if (!Instance.RegisteredHashes.Contains(hash))
{
Instance.RegisteredHashes.Add(hash);
}
return hash;
}
public static void Reset()
{
foreach (string registeredHash in Instance.RegisteredHashes)
{
Instance.Reset(registeredHash);
}
}
protected void Reset(string hash);
}
interface IData{}
interface IDataProvider
{
string GetRedisHash();
IData GetData();
}
intefrace IRedisRepository
{
}
如何使它的工作?
您不一定需要创建实例。一旦任何静态方法或属性被调用,它们将被初始化。是否有什么原因需要它们在你使用它们之前自动初始化? – TyCobb
你可能想检查这个问题。也许一个接口和一些反射会很好地与第二个答案:http://stackoverflow.com/questions/8748492/how-to-initialize-ac-sharp-static-class-before-it-is-actually-needed – TyCobb
这个类是否需要自己注册,或者你是否只想在加载dll时注册类? – FriendlyGuy