[Mono-dev] System.Reflection.Assembly::Load Performance?

Jonathan Pryor jonpryor at vt.edu
Wed Dec 9 10:58:39 EST 2009


On Wed, 2009-12-09 at 16:20 +0100, Leszek Ciesielski wrote:
> This foreach loop is a common pattern for loading subclasses/plugins
> from an assembly, is there a better pattern for this?

Yes: assembly-level attributes.

        http://weblogs.asp.net/justin_rogers/articles/61042.aspx

See the "1. Assembly Attribute Marking" section.

In short, you'd add a new attribute:

        [AttributeUsage(AttributeTargets.Assembly, AllowMultiple=true)]
        class PluginAttribute : Attribute {
                public PluginAttribute (Type type) {this.Type = type;}
                public Type Type {get; private set;}
        }

Then specify this attribute at the assembly level:

        [assembly:Plugin (typeof(Plugin1))]
        [assembly:Plugin (typeof(Plugin2))]
        // ...

Then query the assembly for all the PluginAttributes:

        Assembly a = ...;
        PluginAttribute[] plugins =
                (PluginAttribute[]) a.GetCustomAttributes (
                        typeof(PluginAttribute), true);
        foreach (var plugin in plugins)
                // plugin.Type is the type to use as a plugin

This can be significantly faster than using Assembly.GetTypes(), as only
the types which are listed in [assembly:Plugin] attributes actually need
to be loaded, which can significantly decrease the amount of memory
consumed (depending on the number of types in the assembly).

 - Jon




More information about the Mono-devel-list mailing list