I have a solution that includes 2 projects:
The dll has a reference to another dll (b)
The console application project has only reference to the dll (a)
The dll (b) has a generic singleton class :
public class Singleton<T> where T : class
{
private static T instance;
public static T Instance
{
get
{
return instance;
}
}
static Singleton()
{
instance = (T)Activator.CreateInstance(typeof(T), true);
}
}
The dll (a) has a class Logger that inherits from this class. In the console application program I create an instance of the logger class.
When rebuilding the project, I get this error:
The type 'CSUtilities.Singleton`1' is defined in an assembly that is not referenced. You must add a reference to assembly 'CSUtilities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
When I add a reference to dll(b) to the console app project the problem is solved.
My question is: why do I need to add a reference for dll (b) if I already have a reference for dll (a)?
In the console application program I create an instance of the logger class.
Right - so you're creating an instance of a type which derives from Singleton<T>
. (We'll leave aside the design issue of having a singleton you can subclass, or that apparently has a public constructor...)
Suppose you then write:
instance.SomeMethod();
How is the compiler meant to know how that can be resolved if it doesn't know about Singleton<T>
? Singleton<T>
is effectively part of the API of your subclass... so there has to be a reference to it.
That's at compile-time... additionally, you'd need the DLL containing Singleton<T>
at execution time anyway. That's where you can end up with a stickier issue, if you need to add a reference to something that isn't needed at compile-time, because the dependency is only used in the internal implementation of the library you're actually referring to. It always feels ugly to me, but it makes perfect sense in other ways, as you definitely need the DLL to be present at execution-time.
See more on this question at Stackoverflow