user1145533
user1145533

Reputation: 697

C++/CLI Attributes

I am trying to create a custom attribute that will allow a method in each of my Custom Control libraries to initialise at runtime. I have managed to get this to work using reflection as follows:

InitOnload::initialise()
{
     // get a list of types which are marked with the InitOnLoad attribute
     array<System::Reflection::Assembly^>^ assemblies = System::AppDomain::CurrentDomain->GetAssemblies();

     for each(System::Reflection::Assembly^ assembly in assemblies)
     {
        try
        {
                System::Type^ type = System::Type::GetType("INITONLOAD.InitOnload");

                array<Object^>^ attributes = assembly->GetCustomAttributes(type, false);

           if(attributes->Length > 0)
           {
              auto field =
                 type->GetFields(
                 System::Reflection::BindingFlags::Static | 
                 System::Reflection::BindingFlags::Public | 
                 System::Reflection::BindingFlags::NonPublic);
           }
          }
        catch (...)
        {
        }
      }
}

Foo2 gets initialised at startup, but only if it is defined in the same namespace as InitOnload above.

[assembly: InitOnload()];
public ref class foo2 : public System::Attribute 
{
public:
    foo2()
    {
    };

};

If I try to initilaise a method in a different Custom Control Library it doesn't initilaise foo2 below doesn't initilalise:

[assembly: INITONLOAD::InitOnload()];
public ref class foo : public System::Attribute 
{
public:
    foo()
    {
    };

};

Any ideas?

Upvotes: 1

Views: 2667

Answers (1)

Ben Voigt
Ben Voigt

Reputation: 283684

System::AppDomain::CurrentDomain->GetAssemblies() only lists the assemblies that are already loaded. Because .NET does lazy loading, this include all assemblies you referenced.

I suggest that you install a handler for the AppDomain::AssemblyLoad event and process the types in future assemblies as they are loaded.

Upvotes: 1

Related Questions