Search code examples
c#genericsannotationsservicestackaction-filter

Passing/exposing T on a ServiceStack request filter


I've got a request attribute that I'm decorating some services, but I need to pass a generic type into it because of some logic happening inside of it. It looks like so:

[SomeAttribute(typeof(MyClass))]

This works well, but if I do something such as...

[SomeAttribute<MyClass>]

... I'll get an "Annotations cannot be generic" compile-time error.

Inside my attribute execute logic, I need to do the following:

someClass.doSomething<MyClass>(someString);

So, my question is...

  • Can I cast MyClass to some form of T so I can use it that way?
  • Is there another way I can pass T in the attribute without getting a compile error?

Thanks so much!


Solution

  • As the error messages says .NET Annotations can't be generic so you can only pass in a late-bound Type. The only way to call a generic method from a late-bound Type is to use reflection, e.g:

    var mi = typeof(MyClass).GetMethod("doSomething");
    var genericMi = mi.MakeGenericMethod(typeof(MyAttributeType));
    var doSomethingFn = (Func<string, object>) genericMi.CreateDelegate(
      typeof(Func<string, object>));
    

    Then you can cache and call the compiled delegate of the generic method which takes a string and returns an object, e.g:

    object response = doSomethingFn(someString);