Using .Net6 Azure function I am trying to refactor out an existing set of logic to return an object of type T vs the current void. The current solution is first with my attempt below:
CURRENT
The current closed IHandler code/implementation is
IHandler.cs
{
Task HandleAsync(IMessage message, CancellationToken cancellationToken);
}
and in program.cs
services.AddScoped<Func<MessageType, IHandler>>(sp =>
dataType =>
{
switch (dataType)
{
case MessageType.HandleA:
return sp.GetService<HandleA>();
case MessageType.HandleB:
return sp.GetService<HandleB>();
Implementation
public class HandleA: IHandler
{
public async HandleAsync(IMessage message, CancellationToken cancellationToken)
{ ... //do work in here
}
}
PROPOSED ATTEMPT
The Problem: What I would like to do is create a handler that returns a generic object but the delegate in program is messing with my head. Current (not compiling, but can't see way out)
public interface ISvcMessageHandler<T> : IHandler where T : class
{
Task<List<T>> ReturnObject(IMessage message, CancellationToken cancellationToken);
}
program.cs The issue here is that I have to strongly declare T with a concrete class
//obviously T is not known here.
services.AddScoped<Func<MessageType, ISvcMessageHandler<T>>>(sp =>
dataType =>
{
switch (dataType)
{
case MessageType.HandleA:
return sp.GetService<HandleA<DtoA>>();
case MessageType.HandleB:
return sp.GetService<HandleB<DtoB>>();
Implementation
public class HandleA: ISvcMessageHandler<DtoA>
{
public async Task<List<DtoA>> ReturnObject(IMessage message, CancellationToken cancellationToken)
{
....do work
return foo;
}
}