Searching for attributes

  • Thread starter Thread starter Wernfried Schwenkner
  • Start date Start date
W

Wernfried Schwenkner

I want to implement custom attributes. They can be used in several
assemblies. I want these attributes to register somehow. So I need the
attributes constructor to be called when an attributes is assigned to a
class (in several assemblies).

I found out, that the construtor is only called, when I "search" for
custom attributes in an assembly. Can this be done another way? If not,
how can I "search" in all assemblies?
 
If I understand you correctly, you can write a static Register method for
your attribute and call it the first thing your first assembly is run, and
write a static constructor for your attribute. Here is an example:

public class MyCustomAttribute : Attribute
{
static MyCustomAttribute()
{
Console.WriteLine("MyCustomAttribute constructor called");
}

public static vois Register()
{
// Do something to register the attribute
}
}

[MyCustom]
public class A
{
public A()
{
}

public void Search()
{
Console.WriteLine("Search started...");
// Write your search code here
}

public static void Main()
{
// This can be called in the init method of an assembly
MyCustomAttribute.Register();
A a = new A();
a.Search();
}
}

Angie
 
If I understand you correctly, you can write a static Register method for
your attribute and call it the first thing your first assembly is run, and
write a static constructor for your attribute. Here is an example:

As far as I know, a static constructor is called only once. And I want
to register the class the attributed is assigned on, not the attribute.

It is no problem to search an assembly for all occurences of my custom
attribute. But I don't know how to detect all the assemblies of my
application.
 
Wernfried Schwenkner said:
It is no problem to search an assembly for all occurences of my custom
attribute. But I don't know how to detect all the assemblies of my
application.

You can find all the assemblies loaded within any particular AppDomain
using AppDomain.GetAssemblies. If you can get in early enough, you
could also just subscribe to the AppDomain.AssemblyLoad event, and fix
things up every time an assembly is loaded.
 
Back
Top