Advertisement
Guest User

Untitled

a guest
Jul 25th, 2016
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. using System;
  2. using System.ComponentModel.Composition;
  3. using System.ComponentModel.Composition.Hosting;
  4.  
  5. namespace MefGenericExportImports
  6. {
  7. [Export]
  8. public class Program
  9. {
  10. [Import]
  11. public GenericThing<int> IntGenericThing { get; set; }
  12.  
  13. [Import]
  14. public GenericFuncThing<int> FuncIntGenericThingWorkaround { get; set; }
  15.  
  16. static void Main(string[] args)
  17. {
  18. using (var catalog = new ApplicationCatalog())
  19. using (var container = new CompositionContainer(catalog))
  20. {
  21. container.GetExportedValue<Program>().Run(args);
  22.  
  23. // But this fails: Generics can only go one level deep?
  24. Console.Error.WriteLine("The following exception is expected:");
  25. container.GetExportedValue<GenericThing<Func<int>>>();
  26. }
  27. }
  28.  
  29. void Run(string[] args)
  30. {
  31. Console.WriteLine($"One very indirect way of getting default value of int: {IntGenericThing.Value}");
  32. Console.WriteLine($"Workaround (one way to get null!): {FuncIntGenericThingWorkaround.Value}");
  33. }
  34. }
  35.  
  36. [Export]
  37. public class GenericThing<T>
  38. {
  39. public T Value { get; set; }
  40. }
  41.  
  42. // Workaround is to have the demander just supply the arguments of Func<T> rather than
  43. // provide Func<T> as a type parameter.
  44. [Export]
  45. public class GenericFuncThing<TResult>
  46. {
  47. public Func<TResult> Value { get; set; }
  48. }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement