Reputation: 50190
I have a central service (inside a very large online system) where classes register themselves as 'foo', providers. When the system needs to get some foos is calls all the registered providers. My problem is that the natural place to make the class register itself is in a static constructor; but the static constructor only gets called when part of that class gets called.
static Widdler()
{
FooManager.RegisterProvider(() => GetMyFoos());
}
But that might not happen for some time - the classes provide other services; they may be used a lot or a little.
Can I force these static constructions somehow?
Can anybody think of a better way? (These are not dynamically loaded plugins - in that case as part of loading I would inspect them for some interface like IFooProvider).
EDIT: OK - I cant control when the constructor is called. What should I use instead? My central service does not know about these providers directly. So calling an 'init' function is not on. I am trying to think of a pub sub model like an event bus but this isn't the same. The 'subscriber' needs to call the 'publishers' when it needs something (as opposed to getting called when something happens)
Upvotes: 0
Views: 623
Reputation: 127563
Normally the way to solve this problem is you use a framework like Unity and have that take the place of your RegisterProvider
What you would do is have unity search for all classes that implement IFooProvider
in the assemblies you specify via the "Registration by Convention" system and will load them automatically.
Then in the code where you need a list of all classes that implement IFooProvider
you just call container.ResolveAll<IFooProvider>
and it will return a IEnumerable<IFooProvider>
of all the classes it detected that implements the interface.
Upvotes: 2