4

Heres my issue. I have different types of methods which make HTTP requests to a REST api. To keep things clean, I have methods that take different types of request objects as parameters. Example below.

Task<IEventResponse> FindEventAsync(IGetEventsRequest data, CancellationToken token);

So everytime my controller calls this method, it has to create a object of type IGetEventsRequest. Creating a new() instance of its implementation feels dumb, and I started thinking about creating a generic factory which could create these objects for me, and also work for all kinds of object types. Any help how could I achieve this?

I am looking for this kind of syntax:

await FindEventsAsync(_requestFactory.Create(?somehow specify the type of this and generate a new object based on the type), CancelationToken.None);
  • 1
    How do those different types of request objects as parameters relate to IGetEventsRequest data you want to create? What is the IGetEventsRequest, so it can be used for any request? If IGetEventsRequest is just a set of key-value pairs, while request objects are plain DTOs you can use a bit of reflection to generate the set from input object properties, and then initialize some class GenericGetEventsRequest: IGetEventsRequest with that data. – Eugene Podskal Feb 26 '17 at 20:33
  • Usually type parameters to be instantiated are implemented as generic type parameters, but a Type can be passed instead, using reflection to instantiate. Another technique is to pass a delegate that creates an instance as needed. See Func. – Frank Hileman Mar 10 '17 at 8:27
1

I'm not quite seeing why this is a challenge. Here is a barebones example.

interface IGetEventsRequest
{
}

class SomeRequest : IGetEventsRequest
{
    //Your implementation here
}

class RequestFactory
{
    public T Create<T>() where T: IGetEventsRequest, new()
    {
        T o = new T();
        //Add initialization code here
        return o;
    }
}

class Example
{
    private readonly RequestFactory _requestFactory;

    public Example(RequestFactory requestFactory)
    {
        _requestFactory = requestFactory;
    }

    void Test()
    {
        await FindEventsAsync(_requestFactory.Create<SomeRequest>(), CancelationToken.None);
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.