Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8790135
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T22:34:25+00:00 2026-06-13T22:34:25+00:00

Lately I seem to be working with lots of request/response stuff and I thought

  • 0

Lately I seem to be working with lots of request/response stuff and I thought of creating something generic.

I have the following but I am not happy about creating multiple ifs statements and I would like to avoid them.

The idea is this:

Regardless of the request /response process them.
How can I remove these if statement within my generic request Handler?

Code

class Program
{
    private static void Main()
    {
        IRequestResponseFactory factory = new RequestResponseFactory();

        var customerRequest = new CustomerRequest { Name = "Joe", Surname = "Bloggs" };
        var customerResponse = factory.ProcessRequest<CustomerRequest, CustomerResponse>(customerRequest);

        var billRequest = new BillRequest() { Amount = 100m };
        var billResponse = factory.ProcessRequest<BillRequest, BillResponse>(billRequest);

        Console.WriteLine(billResponse.Success);
        Console.WriteLine(customerResponse.Success);
        Console.ReadKey();

    }
}


public class CustomerRequest : IRequestData<CustomerResponse>
{
    public string Name { get; set; }
    public string Surname { get; set; }
}

public class CustomerResponse
{
    public bool Success { get; set; }
}
public class BillRequest : IRequestData<BillResponse>
{
    public decimal Amount { get; set; }
}
public class BillResponse
{
    public bool Success { get; set; }
}
public interface IRequestData<TResponse>
{
}

public interface IRequestHandler<TRequest, TResponse> where TRequest : IRequestData<TResponse>
{
    TResponse ProcessRequest(TRequest request);
}

public interface IRequestResponseFactory
{
    TResponse ProcessRequest<TRequest, TResponse>(TRequest request) where TRequest : IRequestData<TResponse>;
}
class RequestResponseFactory : IRequestResponseFactory
{
    public TResponse ProcessRequest<TRequest, TResponse>(TRequest request) where TRequest : IRequestData<TResponse>
    {
        var handler = new GenericRequestHandler<TRequest, TResponse>();
        TResponse response = handler.ProcessRequest(request);
        return response;
    }
}
public class GenericRequestHandler<TRequest, TResponse> : IRequestHandler<TRequest, TResponse> where TRequest : IRequestData<TResponse>
{
    public TResponse ProcessRequest(TRequest request)
    {
        var response = default(TResponse);

        //How do I avoid this if statements????

        if (request is IRequestData<CustomerResponse>)
        {
            var tempResponse = new CustomerResponse { Success = true };
            response = (TResponse)Convert.ChangeType(tempResponse, typeof(TResponse));
            return response;
        }
        if (request is IRequestData<BillResponse>)
        {
            var tempResponse = new BillResponse { Success = false };
            response = (TResponse)Convert.ChangeType(tempResponse, typeof(TResponse));
            return response;
        }
        return response;
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T22:34:27+00:00Added an answer on June 13, 2026 at 10:34 pm

    You can replace the GenericRequestHandler<TRequest, TResponse> class with specialized IRequestHandlers and have the factory keep track of all available such handlers via reflection.

    Concretely, these could be the handlers:

    public class CustomerRequestHandler : IRequestHandler<CustomerRequest, CustomerResponse>
    {
        public CustomerResponse ProcessRequest(CustomerRequest request)
        {
            return new CustomerResponse { Success = true };
        }
    }
    
    public class BillRequestHandler : IRequestHandler<BillRequest, BillResponse>
    {
        public BillResponse ProcessRequest(BillRequest request)
        {
            return new BillResponse { Success = false };
        }
    }
    

    Now, the factory, instead of just forwarding the call to the generic handler that contains the if ugliness, will do the following:

    • initialize itself by scanning the current assembly (and possibly other assemblies as well) for types that implement IRequestHandler<TRequest, TResponse>
    • will build a dictionary of handler types, where the key is the TRequest type and the value is the handler type
    • on any incoming request it checks the handler list to see if that particular type can be handled and:
      • delegates the work to the available handler
      • throws an exception if no suitable handler is found

    This is a possible implementation for the factory class:

    class RequestResponseFactory : IRequestResponseFactory
    {
        private readonly Dictionary<Type, Type> _requestHandlerTypes;
    
        public RequestResponseFactory()
        {
            _requestHandlerTypes =
                typeof(RequestResponseFactory).Assembly.GetTypes()
                    .Where(t => !t.IsAbstract)
                    .Select(t => new
                    {
                        HandlerType = t,
                        RequestType = GetHandledRequestType(t)
                    })
                    .Where(x => x.RequestType != null)
                    .ToDictionary(
                        x => x.RequestType,
                        x => x.HandlerType
                    );
        }
    
        private static Type GetHandledRequestType(Type type)
        {
            var handlerInterface = type.GetInterfaces()
                .FirstOrDefault(i =>
                    i.IsGenericType &&
                    i.GetGenericTypeDefinition() == typeof(IRequestHandler<,>));
    
            return handlerInterface == null ? null : handlerInterface.GetGenericArguments()[0];
        }
    
        public TResponse ProcessRequest<TRequest, TResponse>(TRequest request) where TRequest : IRequestData<TResponse>
        {
            if (!_requestHandlerTypes.ContainsKey(typeof(TRequest)))
                throw new ApplicationException("No handler registered for type: " + typeof(TRequest).FullName);
    
            var handlerType = _requestHandlerTypes[typeof(TRequest)];
    
            var handler = (IRequestHandler<TRequest, TResponse>)Activator.CreateInstance(handlerType);
    
            return handler.ProcessRequest(request);
        }
    }
    

    The complete program with working sample is available at http://ideone.com/TxRnEi.

    The output is the same as the output of the original program, but now the program allows you to add new types of requests and new types of handlers and will be able to dynamically use them at run time, without you having to write the long if/case statements to specify when they should be used.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have been working in WPF web browsers lately but I can't seem to
I have been working on packing a project lately but it has turned into
Lately I have become a huge fan of XSL, XPath and XML, but I've
I've taken a dive into FPDF lately and something that i don't seem to
I have been browsing the Google Plus APIs lately and I can't seem to
I have been picking my brain lately and can't seem to figure out how
Not sure if there is a definite answer for this, but I have an
I've been working with ASP.NET MVC and Javascript/jQuery a lot lately and I seem
My company has acquired several companies lately. We are a Java shop but have
I have been working on interfaces lately and I have many problems with imagebutton

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.