-
How do I do this?
I have two C# .NET projects that are loaded into one application process. Each have a reference to the same common library (let's call this common library the plugin). This plugin library needs to be a singleton instance. I've noticed that when each of my project references this plugin library they each have their own copy of the library itself when the application is loaded.
How do I go about making the plugin library a shared library across both of my .NET projects. Thanks
-
Re: How do I do this?
Assuming both projects are in the same application, you should create singleton plugin like so:
Plugin:
Code:
namespace Plugin
{
public class SomePlugin
{
// Return private instance.
public static SomePlugin GetInstance()
{
return sInstance;
}
// Initialized when class comes into scope.
static SomePlugin()
{
sInstance = new SomePlugin();
}
// Keep singleton private.
private static SomePlugin sInstance;
}
}
App1:
Code:
using Plugin;
namespace AppOne
{
public class ApplicationOne
{
public SomePlugin GetPlugin()
{
return SomePlugin.GetInstance();
}
public ApplicationOne() { }
}
}
App2:
Code:
using Plugin;
namespace AppTwo
{
public class ApplicationTwo
{
public SomePlugin GetPlugin()
{
return SomePlugin.GetInstance();
}
public ApplicationTwo() { }
}
}
Main console app:
Code:
using System;
using AppOne;
using AppTwo;
using Plugin;
namespace SingletonExample
{
class Program
{
static void Main(string[] args)
{
ApplicationOne appOne = new ApplicationOne();
ApplicationTwo appTwo = new ApplicationTwo();
SomePlugin pluginTemp1 = appOne.GetPlugin();
SomePlugin pluginTemp2 = appTwo.GetPlugin();
if (pluginTemp1.Equals(pluginTemp2))
{
Console.WriteLine("They're the same");
}
else
{
Console.WriteLine("They're different");
}
Console.ReadLine();
}
}
}
Output from above is: "They're the same"