I have a class like this
public class BonusImageHandler
{ private static IStorageProvider _storageProvider;
private static Type storageProviderType;
private static readonly object _lock = new object();
private static IStorageProvider StorageProvider
{
get
{
lock (_lock)
{
if (_storageProvider == null)
{
lock (_lock)
{
_storageProvider = (IStorageProvider)Activator.CreateInstance(storageProviderType);
}
}
}
return _storageProvider;
}
}
public BonusImageHandler(string providerTypeName)
{
storageProviderType = Type.GetType(providerTypeName);
}
public void ProcessRequest(HttpContext context)
{
//do some thing here
}
private static string ParseInputs(string baseUrl, string imageType)
{
//do other things
}
}
the constructor is not static because it takes a string as an argument and the property private static IStorageProvider StorageProvider is a static one. Team leader told me it will not work this way, why?? how can I test it?? how can I pass the httpContext to the ProcessRequest function.
I’m sorry for this silly question but I’m still a beginner.
This is bad because an instance constructor assigns the static field; consider:
now… what is the static
storageProviderType, and why should that make sense? What handler doesxuse? (hint: it isn’t"foo").Now consider multiple callers, perhaps on different threads, calling this seemingly at random.
Frankly, it looks like this should be more like:
but by the time you’ve done that, you then start thinking maybe it should be:
or even clearer:
Or: just make it an instance field, so you can pass (perhaps via an IoC/DI tool) the provider into each instance separately, i.e.