Reputation: 1100
I'm building a protocol handler. The protocol may support an unknown set of request types, and I will have a single class that implements each request type. These request handler classes will extend a base handler class. I'm trying to build the system such that in order to support a new request type, all I need to do is add a class for that and recompile/deploy/restart the service.
So I have something like this:
foreach (Type classType in protocolAssembly.GetTypes())
{
if (classType.BaseType == typeof(ProtocolRequestHandler))
{
if (supportedRequestsMap.Contains(classType.Method))
{
// error: that method is already implemented!
}
supportedRequestsMap.Add(classType.Method, typeof(classType));
}
}
Adding a new class is picked up when the service restarts, as long as the request method it handles is declared.
How can I enforce at compile time through through the base class ProtocolRequestHandler that property Method will be implemented? I don't want to use a method type as "Null" or "Unknown", or throw exceptions, and I don't want to specify the supported protocol request type inherently in the name of the extending classes (I would like to call the classes whatever I like).
Is there some way I can enforce that a property has its value set in an inheriting class?
Is there a cleaner way I can do this kind of dynamic loading? Should I be using attributes to determine the supported method of the inheriting class?
Upvotes: 4
Views: 347
Reputation: 17956
If you are using a base class, why don't you just create your required method as an abstract method (or virtual and specify a default implementation if possible). This will ensure that the method exists in your inherited class. I believe you probably already know this if you are into reflection and writing your own protocol handler, but am not sure there is a better way to get what you want.
Upvotes: 0