Skip to content

Instantly share code, notes, and snippets.

@binki
Created July 25, 2016 18:39
Show Gist options
  • Save binki/c69c929de9021315d24312b6c21d79a7 to your computer and use it in GitHub Desktop.
Save binki/c69c929de9021315d24312b6c21d79a7 to your computer and use it in GitHub Desktop.
MEF only supports generic type closure using nongeneric type as generic type parameters
using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
namespace MefGenericExportImports
{
[Export]
public class Program
{
[Import]
public GenericThing<int> IntGenericThing { get; set; }
[Import]
public GenericFuncThing<int> FuncIntGenericThingWorkaround { get; set; }
static void Main(string[] args)
{
using (var catalog = new ApplicationCatalog())
using (var container = new CompositionContainer(catalog))
{
container.GetExportedValue<Program>().Run(args);
// But this fails: Generics can only go one level deep?
Console.Error.WriteLine("The following exception is expected:");
container.GetExportedValue<GenericThing<Func<int>>>();
}
}
void Run(string[] args)
{
Console.WriteLine($"One very indirect way of getting default value of int: {IntGenericThing.Value}");
Console.WriteLine($"Workaround (one way to get null!): {FuncIntGenericThingWorkaround.Value}");
}
}
[Export]
public class GenericThing<T>
{
public T Value { get; set; }
}
// Workaround is to have the demander just supply the arguments of Func<T> rather than
// provide Func<T> as a type parameter.
[Export]
public class GenericFuncThing<TResult>
{
public Func<TResult> Value { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment