Issue setting up Singleton
In my project, I have a Singleton which I want to use in certain files. When I try to implement it in one I get an error. First, let me show some code:
The singleton:
The singleton:
public sealed class RegularPuzzleSingleton : ISingleton
{
private const int TrimLength = 13;
private Dictionary<string, Type> _regularTypes;
public IRegularPuzzle RegularPuzzle { get; private set; }
private RegularPuzzleSingleton()
{
GetRegularTypes();
}
public static RegularPuzzleSingleton _instance;
public static RegularPuzzleSingleton GetInstance()
{
_instance ??= new RegularPuzzleSingleton();
return _instance;
}
public void GetRegularTypes()
{
var interfaceType = typeof(IRegularPuzzle);
var implementingTypes = AppDomain.CurrentDomain
.GetAssemblies()
.SelectMany(a => a.GetTypes())
.Where(type => interfaceType.IsAssignableFrom(type)
&& !type.IsAbstract
&& !type.IsInterface);
foreach (var type in implementingTypes)
{
string name = type.Name.ToLower()[..(type.Name.Length - TrimLength)];
_regularTypes[name] = type;
}
}
public bool IsRegularType(string extension)
{
if (_regularTypes.TryGetValue(extension, out Type? regular) && regular != null)
{
RegularPuzzle = (IRegularPuzzle)Activator.CreateInstance(regular);
return true;
}
return false;
}
}public sealed class RegularPuzzleSingleton : ISingleton
{
private const int TrimLength = 13;
private Dictionary<string, Type> _regularTypes;
public IRegularPuzzle RegularPuzzle { get; private set; }
private RegularPuzzleSingleton()
{
GetRegularTypes();
}
public static RegularPuzzleSingleton _instance;
public static RegularPuzzleSingleton GetInstance()
{
_instance ??= new RegularPuzzleSingleton();
return _instance;
}
public void GetRegularTypes()
{
var interfaceType = typeof(IRegularPuzzle);
var implementingTypes = AppDomain.CurrentDomain
.GetAssemblies()
.SelectMany(a => a.GetTypes())
.Where(type => interfaceType.IsAssignableFrom(type)
&& !type.IsAbstract
&& !type.IsInterface);
foreach (var type in implementingTypes)
{
string name = type.Name.ToLower()[..(type.Name.Length - TrimLength)];
_regularTypes[name] = type;
}
}
public bool IsRegularType(string extension)
{
if (_regularTypes.TryGetValue(extension, out Type? regular) && regular != null)
{
RegularPuzzle = (IRegularPuzzle)Activator.CreateInstance(regular);
return true;
}
return false;
}
}