AllowMultiple

Aug 12, 2010 at 2:14 PM

Hi,

How "AllowMultiple" attribute works while implementing Custom Export attribute?

I have two classes "EmailSender" & "SecureEmailSender" those are implementing "IMessageSender" via Custom Export attribute.

Code Snippet of my Custom ExportAttribute called "MessageSenderAttribute" which is being used by above two classes:

[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class,AllowMultiple=false)]
public class MessageSenderAttribute : ExportAttribute
{
     public MessageSenderAttribute() : base(typeof(IMessageSender)) 
     {
     }
        
     public MessageTransport Transport { get; set; }
        
     public bool IsSecure { get; set; }

}

And I am importing it like
 [ImportMany]
 public Lazy<IMessageSender,IMessageSenderCapabilities>[] Senders { get; set; }

Now If I make AllowMultiple = true then it gives me error executing ComposeParts() method.

Can someone help me to understand usage of AllowMultiple parameter?

- Thanks

Aug 12, 2010 at 5:55 PM

The AttributeUsageAttribute is an metadata attribute for telling the compiler how to use the attribute. Attributes can be specified on all visible program elements in the System.Reflection namespace, even return types. The AttributeUsage changes where the attribute is applicable. It's one of those meta meta things.

This has nothing to do with MEF though, it just says something about the attribute usage. For instance, you can restrict an attribute to only be permitted on class definitions. You can also say that the attribute is inherited, that way you inherit attributes when you derive from existing classes with existing attributes.

The AllowMultiple property just says whether you can specify this attribute more than once on the same program element. I rarely find myself using this, but it can be done. If you have an attribute with the AllowMultiple property set to true, you can specify several of those attributes on the same program element. i.e. multiple export definitions for the same part.

Ultimately, you should not have to specify the AttributeUsage to be able to work with MEF, I suggest you ignore it, for now and remove it from you code, until you come up with a scenario where you actually do need it.

Aug 13, 2010 at 5:13 AM

Hi Leidegre,

Thanks for giving me explanation on AllowMultiple attribute. This is very useful.

- Thanks again.