public class SharedCacheData : ISharedCacheData
{
private readonly ISharedPetsService mPetsService;
private static ISharedEmployeeService mSharedEmployeeService;
public SharedCacheData(ISharedPetsService petsService, ISharedEmployeeService employeeService)
{
mPetsService = petsService;
mSharedEmployeeService = employeeService;
}
public static string GetUserFullName(string key)
{
Hashtable value = HttpContext.Current.Application[USERFULLNAME_KEY] as Hashtable;
if (value == null)
{
value = new Hashtable();
HttpContext.Current.Application[USERFULLNAME_KEY] = value;
}
if (value.ContainsKey(key))
return value[key] as string;
string name = mSharedEmployeeService.FindOneUser(key);
value[key] = name;
return name;
}
Whether initialize static field mSharedEmployeeService (service) in constructors?
You can define a static field using the static keyword. If you declare a static variable in a class, if you haven't initialized it, just like with instance variables compiler initializes these with default values in the default constructor. Yes, you can also initialize these values using the constructor.
A class or struct can only have one static constructor. Static constructors cannot be inherited or overloaded. A static constructor cannot be called directly and is only meant to be called by the common language runtime (CLR). It is invoked automatically.
Initialization of Instance variables But if you declare an instance variable static and final Java compiler will not initialize it in the default constructor therefore, it is mandatory to initialize static and final variables. If you don't a compile time error is generated.
A static variable can be accessed without an object, therefore the variable shouldn't be static if you need to initialize in the constructor. It makes no sense to "initialize" a static member in a constructor. It will get reinitialized every time you create a new instance.
No, that's generally a bad idea. Every time you create a new instance, it will be replacing the static variable. That's almost certainly not what you want to do.
I wonder whether actually there should be two classes here - one for the pets service and one for the employee service. It's hard to tell from the code presented, but what we've got here really doesn't look like a good idea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With