Reputation: 1621
Suppose I have 3 DLL's. DLL #1 and #2 depend on DLL #3. DLL #3 contains a static class such as:
public class ImportTimer
{
public static bool EnableProcessorTimerLogging { get; set; }
public static bool EnableTimerLogging { get; set; }
public static DateTime SourceDataDetectionTimestamp { get; set; }
public static DateTime LastEndProcessTimestamp { get; set; }
static ImportTimer()
{
EnableProcessorTimerLogging = false;
EnableTimerLogging = false;
SourceDataDetectionTimestamp = DateTime.Now;
LastEndProcessTimestamp = DateTime.Now;
}
...
}
All of the methods are static. DLL #1 and #2 do not know about each other (no dependencies on the other). When I invoke any method from DLL #1 and then invoke the same method on DLL #2, I see a new copy of the static object get created in DLL #2 (it is not using the same copy as DLL #1). So now I have 2 copies of ImportTimer when I only wanted one for both DLL's to share. How can I get the 2 DLL's to share the same static instance?
Upvotes: 0
Views: 4262
Reputation: 36287
Your class is not static. The static
constructor lets you initialize static members, it's called automatically before your class is instantiated.
You can mark you class as static
as well, by doing static class ImportTimer
.
a static class remains in memory for the lifetime of the application domain in which your program resides.
However, this means you cannot have anything but static members in your class.
Alternatively, you can use a pattern to ensure that there is only 1 instance created, for that you can use the Singleton Pattern.
In your ImportTimer
, you want to set your constructor to private
. Why? Because that way no one else but the class can create the instance.
Add a static property to get an instance of your class:
private static ImportTimer instance;
public static ImportTimer Instance
{
if(instance == null) instance = new ImportTimer();
return instance;
}
Then in DLL #1 and #2, you can use ImportTimer.Instance
to get the shared, static instance.
Upvotes: 1