How to export a generic method as delegate using new registration builder

Jun 14, 2011 at 11:58 PM
Edited Jun 15, 2011 at 12:31 AM

How to export a generic method as delegate using new registration builder 

i want to export generic method(Consume(T msg)) inside generic interface Iconsumer<> using registration builder. How can i do that.

below is the code i am using  

 

public interface IConsumerFor
    {
        string MsgType { get; }
    }
 
    public interface IConsumer<T> 
    {
        void Consume(T msg);
    }
    
    public class message
    {
        public string msg { getset; }
    }
 
    public class Consumer : IConsumer<message>
    {
        public void Consume(message1 msg)
        {
            Console.WriteLine("Consumer 1 :" + msg.msg);
        }
    }
 
    [Export(typeof(Messenger))]
    public class Messenger
    {
        [ImportMany(typeof(Delegate), AllowRecomposition = true)]
        public List<ExportFactory<DelegateIConsumerFor>> Subscribers { getset; }
 
        public void Publish(object parameter)
        {
            var name = parameter.GetType().Name.ToLower();
            var subs = Subscribers.Where(import => import.Metadata.MsgType.ToLower().Contains(name)).ToList();
            foreach (var fac in subs)
            {
                using (var export = fac.CreateExport())
                {
                    export.Value.Method.Invoke(export.Value.Target, new object[] { parameter });
                }
            }
        }
    }
 
 
    class Program
    {
        static void Main(string[] args)
        {
            var context = new RegistrationBuilder();
            context.Where(r =>
                {
                    if (r.IsClass)
                    {
                        var itypes = r.GetInterfaces().Where(tp => (tp.IsGenericType && tp.GetGenericTypeDefinition() == typeof(IConsumer<>))).ToList();
                        return itypes != null && itypes.Count > 0;
                    }
                    return false;
                }).Export(c => c.AddMetadata("MsgType", t => t.ToGenericArg()));
 
            var catalogs = new List<ComposablePartCatalog>();
            catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly(),context));
            var container = new CompositionContainer(new AggregateCatalog(_catalogs), CompositionOptions.IsThreadSafe);
 
            Messenger mb = container.GetExportedValue<Messenger>();
            
            message t1 = new message() { msg = "hello 1" };
            mb.Publish(t1);
            
            Console.ReadLine();
        }
    }