Non-lazy static initialization block in C #

I need to run some type registration code for a factory pattern. I would do it in Java with a static initializer or in C ++ with a static constructor.

How do you do this in C #? This static constructor starts lazily, and since the type will never be mentioned in the code, it is never registered.

EDIT: I tried the test to see how the registration code works. This does not seem to work.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

[assembly: AssemblyTest.RegisterToFactory("hello, world!")]

namespace AssemblyTest
{
    [AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = true)]
    sealed class RegisterToFactoryAttribute : Attribute
    {
        public RegisterToFactoryAttribute(string name)
        {
            Console.WriteLine("Registered {0}", name);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}

Nothing is printed.

+5
source share
1 answer

How is the constructor for assembly level attribute?

Example:

[AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = true)]
sealed class RegisterToFactoryAttribute : Attribute
{
    public Type TypeToRegister { get; set; }

    public RegisterToFactoryAttribute(Type typeToRegister)
    {
        TypeToRegister = typeToRegister;

        // Registration code
    }
}

Using:

[assembly:RegisterToFactory(typeof(MyClass))]

- CHANGE Build Level Attributes -

, , :

:

object[] attributes =
    Assembly.GetExecutingAssembly().GetCustomAttributes(
        typeof(RegisterToFactoryAttribute), false);

object[] attributes =
    Assembly.GetExecutingAssembly().GetCustomAttributes(false);

, , @, .

- EDIT -

:

MEF?? .

:

class MyFactory
{
    [ImportMany("MyFactoryExport")]
    public List<Object> Registrations { get; set; }

    public MyFactory()
    {
        AssemblyCatalog catalog = new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly());
        CompositionContainer container = new CompositionContainer(catalog);
        container.ComposeParts(this);
    }
}

[Export("MyFactoryExport")]
class MyClass1
{ }

[Export("MyFactoryExport")]
class MyClass2
{ }

[Export("MyFactoryExport")]
class MyClass3
{ }
+4

All Articles