UPDATE:
Basically, this boils down to "how can I force class libraries to load at Application Start for an Web API site so I can reflect through them once and be sure I get all implementations of a certain class. Alternately, if there's no good way to do this, what's the best way to allow classes in that library to register themselves?
Original Question:
I'm trying to register all classes that implement a certain interface on application start in my Web API and put them in a list, so I can find them later without reflecting through the assembly on each call.
It seems fairly simple, although I've never done it before. So after a bit of googling and reading some other Stack Overflow questions, I created a container class and put a method to register all the concrete implementations. A simplified solution looks something like this:
public static void RegisterAllBots()
{
var type = typeof(IRobot);
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(type.IsAssignableFrom);
foreach (var t in types)
{
TypeRepo.Add(t.Name.ToLower(), t);
}
}
And then I put my RegisterAllBots() in Application_Start() of the Global.asax.
The problem is, sometimes (but not always) if I start debugging the solution "cold," it doesn't find the implementations, only the Interface itself. If I go to Build -> Rebuild Solution before running it, it finds them. So I'm assuming this is an issue with Visual Studio starting up the WebHost Project without rebuilding the other class library projects.
So I have a few questions here.
- Am I right about the cause here?
- How can I stop this?
- As of right now, can this happen in production? I've deployed it to a test site and it seemed to work, but that could just be luck since sometimes it does find the concrete implementations anyway.