Jaylen Jaylen - 1 month ago 7
C# Question

How can I create a wrapper for the Export attribute when using MEF with C#?

I have an application that uses Managed Extensibility Framework (MEF) along with ASP.NET MVC 5. This architecture allows me to have a pluggable design where I can build multiple applications and run all of them into one master application. It also allowed me to have one central place for authentication and permission validation/loading.

For MVC 5 to work with MEF, each controller must have a unique export value. Therefore, I have to add these two line codes to each of my controller

[Export("SomeUniqueValue1", typeof(IController))]
[PartCreationPolicy(CreationPolicy.NonShared)]


To make the export value unique to each plugin, I like to concatenate the plugin name to the export values. so instead of using the 2 lines above, I'll use something like this instead

[Export("PluginName.SomeUniqueValue1", typeof(IController))]
[PartCreationPolicy(CreationPolicy.NonShared)]


Now, I am hoping to save some coding time by eliminating the 2 lines of code above so a single like. I am hoping something like the line below

[MefExport("SomeUniqueValue1")]


Then the
MefExport
class, will handle the concatenation of the plugin name to the provided name and somehow calls the
Export
class and the
PartCreationPolicy


How can I create a class "i.e. MefExport" that extends
Export
class which allows me to add the plugin name and call the
Export
and the
PartCreationPolicy
?

This is what I started with

public class MefExport : ExportAttribute
{
public MefExport(string exportName)
{
string finalExportValue = Helpers.GetPluginName() + exportName;

new ExportAttribute(finalExportValue, typeof(IController));
}
}

Answer

I do not think you can reasonably combine both attributes into one. The PartCreationPolicyAttribute is a sealed class and code which is looking for that attribute will need precisely that type.

However, you could simplify the first bit by calling the base class with your calculated values:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = false)]
public sealed class MefExportAttribute : ExportAttribute
{
    public MefExportAttribute(string exportName)
        : base(GetContractName(exportName), typeof(IController))
    {
    }

    private static string GetContractName(string exportName)
    {
        return Helpers.GetPluginName() + exportName;
    }
}

(I just copied the ExportAttribute's AttributeUsage values - you may have different needs for this custom attribute.)

Comments