Generic method exports

Dec 31, 2011 at 9:55 PM

I would like to do the following composition:

var container = new CompositionContainer(/*instantiate generic catalog somehow here*/);

var client = new MyRepositoryClient();

container.SatisfyImportsOnce(client);

client.SaveMethod(new InputA());

 The trick is the way I am expecting the composition to happen with these classes below.  Is this possible?

/// <summary>
/// This class imports a reference to a "SaveMethod" of the generic repository aggregator,
/// saves the "InputA" object, and writes the response to the console.
/// </summary>
public class MyRepositoryClient
{
    [Import("SaveMethod")]
    public Func<InputAOutputA> SaveMethod { getset; }

    public bool SaveToRepository(InputA input)
    {
        var result = SaveMethod(input);

        Console.WriteLine(result);

        return true;
    }
}

/// <summary>
/// This is the generic repository aggregator.  All it does is import the repositories
/// that match the generic types, and then calls all of them whenever the Save method
/// is called.  Only the response from the first repository is used for the return value.
/// </summary>
/// <typeparam name="TInput"></typeparam>
/// <typeparam name="TOutput"></typeparam>
public class RepositoryAggregator<TInput, TOutput>
{
    [ImportMany("Repository")]
    public IEnumerable<Func<TInput, TOutput>> Repositories { getset; }

    [Export("SaveMethod")]
    public TOutput Save(TInput input)
    {
        var repositories = Repositories.ToArray();

        var result = repositories[0](input);

        foreach (var repository in repositories.Skip(1))
            repository(input);

        return result;
    }
}

/// <summary>
/// This is an unimplemented repository that handles InputA objects.
/// </summary>
public class RepositoryA1
{
    [Export("RepositoryMethod")]
    public OutputA Save(InputA inputA)
    {
        return null;
    }
}

/// <summary>
/// This is another unimplemented repository that handles InputA objects.
/// </summary>
public class RepositoryA2
{
    [Export("RepositoryMethod")]
    public OutputA Save(InputA inputA)
    {
        return null;
    }
}

 


Jan 20, 2012 at 3:49 PM

Can anyone tell me if this type of generic composition is supported?

Coordinator
Jan 23, 2012 at 8:17 AM

No, exporting generic methods is not yet supported by MEFContrib. You can try with MEF2 preview bits, they have nice generic support baked in.

/Piotr