Skip to content

Latest commit

 

History

History
59 lines (47 loc) · 2.52 KB

StateExtensionPoints.md

File metadata and controls

59 lines (47 loc) · 2.52 KB

State Extension Points

Someta allows you to add fields to the class containing your extension point. There are a variety of siutations where you may want to track state for each instance that the extension point is attached to.

Note: static fields are not supported as there's no point. If you need a static field, just declare it in your extension point as a normal static field.

This interface works in conjunction with InjectedField<T>. The purpose of this interface is to act as a marker for whether or not to look for injected fields in your extension point. If injected fields are found, the corresponding properties will be set to a new instance of InjectedField<T> where it's set up in a way that will allow direct access to the field through the injected field's GetValue and SetValue methods.

Example

public void StateExample()
{
    var testClass = new StateExtensionPointTestClass();
    testClass.Run();
    var extensionPoint = testClass.GetType().GetExtensionPoint<StateExtensionPoint>();
    var invocationCount = extensionPoint.GetCurrentValue(testClass);
    Console.WriteLine(invocationCount);     // Prints 1
}

[StateExtensionPoint]
class StateExtensionPointTestClass
{
    public int Value { get; set; }

    public void Run()
    {
    }
}

[AttributeUsage(AttributeTargets.Class)]
class StateExtensionPoint : Attribute, IStateExtensionPoint, IMethodInterceptor
{
    public InjectedField<int> TestField { get; set; } = default!;

    public object? Invoke(MethodInfo methodInfo, object instance, Type[] typeArguments, object[] arguments, Func<object[], object> invoker)
    {
        var value = TestField.GetValue(instance);
        var newValue = value + 1;
        TestField.SetValue(instance, newValue);
        return null;
    }

    public int GetCurrentValue(object instance) => TestField.GetValue(instance);
}

snippet source | anchor