Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to use reflection and abstract objects to dynamically load classes?
    text
    copied!<p>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.</p> <p>So I have something like this:</p> <pre class="lang-cs prettyprint-override"><code>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)); } } </code></pre> <p>Adding a new class is picked up when the service restarts, <em>as long as the request method it handles is declared.</em></p> <p>How can I enforce at compile time through through the base class <strong>ProtocolRequestHandler</strong> that property <strong>Method</strong> 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). </p> <p>Is there some way I can enforce that a property has its value set in an inheriting class?</p> <p>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?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload