For a server I am writing, I have a folder of files, one class in each file.
Each class represent a request action from the client.
If I add a new action, I want to simply be able to add a new file, letting the file register itself.
In language such as Go you can have init functions, one in each file, that runs at initialization, letting you register things like factory delegates (or first class functions).
Can you achieve something similar in C#, letting the files register their own classes without you having to edit a second file containing a list of all registered actions?
// This won't work, but how to do it?
func init() {
// Registering a factory function to a Dictionary<string, Func<IAction>>
Reg.ClassDictionary.Add("connect", () => { return new Connect(); });
}
namespace Action
{
class Connect : IAction
{
[JsonProperty("user")]
public string Username;
[JsonProperty("pass")]
public string Password;
public bool Exec()
{
return ConnectToServer(Username, Password);
}
}
}
If it’s a console app, just do it at the start of your
Mainmethod.If it’s a windows service, when you extend
ServiceBase, you get anOnStartmethod (that you can override) which executes when the service starts. http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase.onstart.aspxHere’s a quick tutorial on Windows Services to get you started: http://www.switchonthecode.com/tutorials/creating-a-simple-windows-service-in-csharp
EDIT: Based on your clarification, AFAIK, there’s no built-in way to have files/types do what you’re asking. However, what you could do is some reflection. You can peruse your assemblies for particular types/interfaces that implement your
IAction(or rather, some other descriptive type). You can search through for all of them, instantiate them, then call their variousinitmethods during the startup phases I described above.