Specifying .Net custom Attributes which are located in another assembly
My questions are:
- Does this look 'correct'? Or is there something fundamental I am missing?
- Since I have a reference to the PluginCo.Load.dll, which holds the custom Attribute I need to specify in my own plugin, this is possible, right?
I am trying to create a .Net DLL to be loaded into a plugin architecture. In order for it to load in the host application, the class and method of my plugin must have a specific Attribute specified. This custom attribute is implemented in a separate DLL for the plugin.
My plugin code I am trying to write is what I believe is the problem. It SHOULD load into the plugin framework because it specifies the CreatedByPluginCo attribute on the class:
using System.Windows.Forms;
using PluginCo.Load;
namespace _test2
{
[CreatedByPluginCo]
public class Class1
{
[CreatedByPluginCo]
public static void Test()
{
MessageBox.Show("If you see this it worked!");
}
}
Here is what the code looks like in the PluginCo.Load.dll:
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple=true, Inherited=false)]
public class CreatedByPluginCoAttribute : Attribute
{
// Fields
private string _stringComment = string.Empty;
// Properties
public string Comment
{
get
{
return this._stringComment;
}
set
{
this._stringComment = value;
}
}
}
For a method to test the presence of the CreatedByPluginCo attribute in my assembly (which I hope to eventually load as a plugin), I put this method together in a small application (requires Reflection):
public static Attribute GetCreatedByPluginCoAttribute(Attribute[] attributes)
{
for (int i = 0; i < attributes.Length; i++)
{
if (attributes[i].GetType().Name.CompareTo(typeof(CreatedByPluginCoAttribute).Name) == 0)
{
return attributes[i];
}
}
return null;
}
and test if this returns null:
if (GetCreatedByPluginCoAttribute(Attribute.GetCustomAttributes(Assembly.LoadFrom(fileName))) == null)
Unfortunately, this method above is returning false when I load my little sample/test plugin DLL. It is returning true for other sample plugins (which I obviously didn't write..).
I am looking at these sample plugins and there isn't much too them - anything that has this attribute on a public class is loadable. I am doing exactly what they are doing..
Any insight appreciat开发者_Python百科ed! Even if its just a simple "that is strange, this looks correct to me", that would help my sanity.
The GetCustomAttributes
overload you are calling returns the custom attributes that are applied at the assembly level, not types or methods.
You will need to enumerate the public types in the assembly, and then examine each to see if it has your attribute applied.
And to answer your other question: No, there are nothing fundamentally wrong with what you are doing (but have you heard of MEF ? Might save you some trouble).
精彩评论