MEF Friendly version of RegisterSerializer

Apr 15, 2011 at 1:54 AM
Edited Apr 15, 2011 at 1:55 AM

I am trying to use MEF to discover all the Serializers in my project, then register them with Sterling.

Typically this would look like:

    [ImportMany(typeof(BaseSerializer))]
    public List<BaseSerializer > DevPortalSerializers;
             
                ...

    foreach (BaseSerializer bs in DevPortalSerializers)
        _engine.SterlingDatabase.RegisterSerializer(bs)  

 Of course, in Sterling, this wont't work. Sterling required the Generic syntax:
     _engine.SterlingDatabase.RegisterSerializer<MyCustomSerializer>();  

The Generic Syntax won't work with MEF, as MEF is a runtime creature, while the Generic syntax is compile time.

Does anyone know a way to get this to work, short of altering the base SterlingDatabase interface?  



--

Chris Mullins

Coordinator
Apr 15, 2011 at 2:30 AM

Generics are run-time. The template is generated by the jitter when encountered. I will look at using an interface that is non-generic, but for now you can absolutely do what you want. You just need to create the method template for the register serializer method and then close the generic.

I'm not building it right now but it will look something like this:

var method = typeof(SterlingDatabase).GetMethod("RegisterSerializer");
foreach (BaseSerializer bs in DevPortalSerializers)
{
    var generic = method.MakeGenericMethod(bs.GetType());
    generic.Invoke(_engine.SterlingDatabase, null);
}
Apr 15, 2011 at 2:32 AM
Edited Apr 15, 2011 at 2:33 AM
That's awesome. It never occured to me to do that with reflection.
--
Chris