14

I want to export a generic class to a generic interface via MEF. My objects are:

public interface IService<T> { }

[Export(typeof(IService<T>))] // error!!!!!!
public class Service<T> { }

public class Client<T> {
    [Import]
    private IService<T> _service;
}

But when I try to export IService<T>, I get this error:

Attribute argument cannot use type parameters

Can anybody guide me to do this please?

Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
amiry jd
  • 27,021
  • 30
  • 116
  • 215
  • By the way i would recommend to specify an interface like: `public class Service where T : IMyInterface` – rekire Feb 15 '12 at 16:28

1 Answers1

26

Try

[Export(typeof(IService<>))]

To get a generic type definition from the typeof operator, you omit type arguments. For types with more than one type parameter, use commas to indicate the "arity" of the type. For example:

typeof(List<>)              // not: typeof(List<T>)
typeof(IDictionary<,>)      // not: typeof(IDictionary<K, V>)
phoog
  • 42,068
  • 6
  • 79
  • 117