Search code examples
c#.netserializationmefxrmtoolbox

MEF, Lazy loading with advanced metadata and serialization exception


I'm developing an application that accepts plugins and I decided to use MEF. Everything worked fine until I tried to use AppDomain and ShadowCopy. Now, when trying to retrieve plugin from the MEF container, I'm facing a serialization exception on the metadata interface.

Here are the several components of my code:

The container:

public class PluginManagerExtended : MarshalByRefObject
    {
        private static readonly string PluginPath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "Plugins");
        private CompositionContainer container;
        private DirectoryCatalog directoryCatalog;            

        [ImportMany(AllowRecomposition = true)]
        public IEnumerable<Lazy<IXrmToolBoxPlugin, IPluginMetadata>> Plugins { get; set; }

        public void Initialize()
        {
            try
            {
                var regBuilder = new RegistrationBuilder();
                regBuilder.ForTypesDerivedFrom<Lazy<IXrmToolBoxPlugin, IPluginMetadata>>().Export<Lazy<IXrmToolBoxPlugin, IPluginMetadata>>();

                var catalog = new AggregateCatalog();
                catalog.Catalogs.Add(new AssemblyCatalog(typeof(PluginManagerExtended).Assembly, regBuilder));

                directoryCatalog = new DirectoryCatalog(PluginPath, regBuilder);
                catalog.Catalogs.Add(directoryCatalog);

                container = new CompositionContainer(catalog);
                container.ComposeParts(this);
            }
            catch (ReflectionTypeLoadException ex)
            {
                if (ex.LoaderExceptions.Length == 1)
                {
                    throw ex.LoaderExceptions[0];
                }
                var sb = new StringBuilder();
                var i = 1;
                sb.AppendLine("Multiple Exception Occured Attempting to Intialize the Plugin Manager");
                foreach (var exception in ex.LoaderExceptions)
                {
                    sb.AppendLine("Exception " + i++);
                    sb.AppendLine(exception.ToString());
                    sb.AppendLine();
                    sb.AppendLine();
                }

                throw new ReflectionTypeLoadException(ex.Types, ex.LoaderExceptions, sb.ToString());
            }
        }

        public void Recompose()
        {
            directoryCatalog.Refresh();
            container.ComposeParts(directoryCatalog.Parts)
        }

        internal void DoSomething()
        {
            Plugins.ToList().ForEach(p => MessageBox.Show(p.Metadata.Name));
        }
}

The metadata interface:

public interface IPluginMetadata
{
    string BackgroundColor { get; }
    string BigImageBase64 { get; }
    string Description { get; }
    string Name { get; }
    string PrimaryFontColor { get; }
    string SecondaryFontColor { get; }
    string SmallImageBase64 { get; }
}

The plugin I'm working with:

[Export(typeof(IXrmToolBoxPlugin)),
ExportMetadata("Name", "A Sample Tool 2"),
ExportMetadata("Description", "This is a tool to learn XrmToolBox developement")
ExportMetadata("SmallImageBase64", null),
ExportMetadata("BigImageBase64", null),
ExportMetadata("BackgroundColor", "Lavender"),
ExportMetadata("PrimaryFontColor", "#000000"),
ExportMetadata("SecondaryFontColor", "DarkGray")]
public class Plugin : PluginBase
{
    /// <summary>
    /// This method return the actual usercontrol that will
    /// be used in XrmToolBox
    /// </summary>
    /// <returns>User control to display</returns>
    public override IXrmToolBoxPluginControl GetControl()
    {
        return new SampleTool2();
    }
}

And the code that uses both elements:

var cachePath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase,
    "ShadowCopyCache");
var pluginsPath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase,
    "Plugins");

if (!Directory.Exists(cachePath))
{
    Directory.CreateDirectory(cachePath);
}
if (!Directory.Exists(pluginsPath))
{
    Directory.CreateDirectory(pluginsPath);
}

var setup = new AppDomainSetup
{
    CachePath = cachePath,
    ShadowCopyFiles = "true",
    ShadowCopyDirectories = pluginsPath
};

domain = AppDomain.CreateDomain("XrmToolBox_AppDomain", AppDomain.CurrentDomain.Evidence, setup);
pManager =
    (PluginManagerExtended)
        domain.CreateInstanceAndUnwrap(typeof(PluginManagerExtended).Assembly.FullName,
            typeof(PluginManagerExtended).FullName);

pManager.Initialize();

// This code works well as the Metadata are accessed in the container
pManager.DoSomething();

// This code fails
string plugins = String.Join(",", pManager.Plugins.Select(p => p.Metadata.Name));

The exception I got is the following:

System.Runtime.Serialization.SerializationException: Type 'proxy_XrmToolBox.Extensibility.Interfaces.IPluginMetadata_bafb7089-c69c-4f81-92f8-a88eda6d70eb' in assembly 'MetadataViewProxies_760ed609-1713-4fe9-959c-7bfa78012252, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.

XrmToolBox.Extensibility.Interfaces.IPluginMetadata is the advanced metadata interface above.

I don't know what "MetadataViewProxies_760ed609-1713-4fe9-959c-7bfa78012252, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null" is

What can I do to fix this error?

Thank you


Solution

  • To access objects in another appdomain they must be serializable. Although you don't seem to be using IPluginMetadata in the code above I assuming it's for a strongly typed custom metadata attribute. Try making whatever implements that Serializable.