Reputation: 663
I want to keep some set of objects in static dictionary (to work as a factory with objects in memory) and avoid instantiation at every time an action is requested. The objects in the factory (objects in memory) do not have any state and the dependencies are passed from outside. I wanted to double check there is No thread safety issues involved here , the sample code is as below:
public interface IDataValidator
{
bool Validate(long identifier);
}
public class ValidatorLocator
{
private static readonly Dictionary<string, IDataValidator> DataValidators = new Dictionary<string, IDataValidator>
{
{ "binary", new BinaryDataValidator()},
{ "hex", new HexDataValidator()}
};
public static IDataValidator GetDataValidator(string valType)
{
return DataValidators.ContainsKey(valType) ? DataValidators[valType] : null;
}
}
public class HexDataValidator : IDataValidator
{
public bool Validate(long identifier)
{
//evaluate business logic
return true;
}
}
public class BinaryDataValidator : IDataValidator
{
public bool Validate(long identifier)
{
//evaluate business logic
return true;
}
}
Please indicate if I am heading for any disaster and any quick guidance is much appreciated. A bit skeptic about threads ( How does this look from an ASP.Net request thread perspective?)
Upvotes: 0
Views: 73
Reputation: 100610
Your sample code is thread safe:
Upvotes: 2