Skip to content

Latest commit

 

History

History
98 lines (81 loc) · 3.61 KB

InstanceInitializers.md

File metadata and controls

98 lines (81 loc) · 3.61 KB

Initializer Extension Points

Someta allows you to inject behavior into the constructor of a target class. We provide two interfaces, one to add behavior at the start of the constructor and the other to add behavior at the end. Sometimes you may want to wait for the constructor of the target class to complete before adding your own logic. For that use IInstanceInitializer. At other times, you may want to instantiate some state (through InjectedField<T>) and initialize it before the constructor of the target class starts so as to make available behavior within the constructor itself.

This interface has one method:

void Initialize(object instance, MemberInfo member);

snippet source | anchor

Example

public void InitializerExample()
{
    var testClass = new InitializerTestClass();
    Console.WriteLine(testClass.Value);         // Prints 1
}

[InitializerExtensionPoint]
class InitializerTestClass
{
    public int Value { get; set; }
}

[AttributeUsage(AttributeTargets.Class)]
class InitializerExtensionPoint : Attribute, IInstanceInitializer
{
    public void Initialize(object instance, MemberInfo member)
    {
        ((InitializerTestClass)instance).Value++;
    }
}

snippet source | anchor

This interface has one method:

object Invoke(MethodInfo methodInfo, object instance, Type[] typeArguments, object[] arguments, Func<object[], object> invoker);

snippet source | anchor

Example

public void PreinitializerExample()
{
    var testClass = new PreinitializerTestClass();
    Console.WriteLine(testClass.ValueAsSeenInConstructor);         // Prints 1
}

[PreinitializerExtensionPoint]
class PreinitializerTestClass
{
    public int Value { get; set; }
    public int ValueAsSeenInConstructor { get; set; }

    public PreinitializerTestClass()
    {
        ValueAsSeenInConstructor = Value;
    }
}

[AttributeUsage(AttributeTargets.Class)]
class PreinitializerExtensionPoint : Attribute, IInstancePreinitializer
{
    public void Preinitialize(object instance, MemberInfo member)
    {
        ((PreinitializerTestClass)instance).Value = 1;
    }
}

snippet source | anchor