How can I find all classes in an assembly that are an instance of a generic abstract class and implement a certain interface ?
Note:
The interface can also be implemented in a class that is inherited from another class that implements the interface.
A concrete example:
I have the bellow interface and Middleware-Class:
public interface IHttpHandler
{
bool IsReusable { get; }
void ProcessRequest(HttpContext context);
}
public abstract class HandlerMiddleware<T> where T: IHttpHandler
{
private readonly RequestDelegate _next;
public HandlerMiddleware()
{ }
public HandlerMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
await SyncInvoke(context);
}
public Task SyncInvoke(HttpContext context)
{
// IHttpHandler handler = (IHttpHandler)this;
T handler = System.Activator.CreateInstance<T>();
handler.ProcessRequest(context);
return Task.CompletedTask;
}
} // End Abstract Class HandlerMiddleware
How can I find all classes like HelloWorldHandler, that implement the abstract class, and implement IHttpHandler.
Note that HandlerMiddleware is generic.
It should find all handlers, e.g. HelloWorldHandler1 and HelloWorldHandler2.
[HandlerPath("/hello")]
public class HelloWorldHandler
: HandlerMiddleware<HelloWorldHandler>, IHttpHandler
{
public HelloWorldHandler() :base() { }
public HelloWorldHandler(RequestDelegate next):base(next) { }
void IHttpHandler.ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
//await context.Response.WriteAsync("Hello World!");
byte[] buffer = System.Text.Encoding.UTF8.GetBytes("hello world");
context.Response.Body.Write(buffer, 0, buffer.Length);
}
bool IHttpHandler.IsReusable
{
get
{
return false;
}
}
}
Bonus points if the method also find this construct:
[HandlerPath("/hello2")]
public class HelloWorldHandler2
: HandlerMiddleware<Middleman>
{
public HelloWorldHandler2() :base() { }
public HelloWorldHandler2(RequestDelegate next):base(next) { }
}
public class Middleman
: IHttpHandler
{
bool IHttpHandler.IsReusable => throw new NotImplementedException();
void IHttpHandler.ProcessRequest(HttpContext context)
{
throw new NotImplementedException();
}
}