Behaviors

Marek Fišera edited this page Sep 17, 2016 · 6 revisions

Behaviors provides abstractions and base classes for implementing custom interception. Such interception is used in pipelines for Jobs, Commands and also in WebStack. Behavior selection is based on implemented interfaces or used attributes and this selection can done be runtime reflection, manual implementation or dynamically compiled tiny proxy.

Behavior selection

As mentioned, behaviors can be selection based on various criteria. Most basic is the hand written and in-place compilation of proxy class. This gives you the ability add behavior without any mark on the inner class.

Interface based provides

More useful provider is based on implemented interfaces. You can create collection of mappings from interface (used on inner class) to behavior implementation type and than by implementing this interface, you can achieve behavior execution. The behavior implementation type must implement IBehavior<T>, where T is the required inner class type. This can be of any type, but when implemented using mapped interface, the most appropriate is the of the interface.

IBehaviorProvider behaviorProvider = new InterfaceBehaviorCollection()
    .Add<ILoggerAware, LoggerAwareBehavior>();

With this mapping and implementation of LoggerAwareBehavior

public class LoggerAwareBehavior : IBehavior<ILoggerAware>
{
    public Task ExecuteAsync(ILoggerAware handler, IBehaviorContext context)
    {
        handler.Logger = new Logger();
        return context.NextAsync();
    }
}

Any class implementing ILoggerAware, and executed inside behavior pipeline, will have the Logger property set to instance of the logger.

public class BackgroundService : ILoggerAware
{
    public ILogger Logger { get; set; }

    ...
}

Attribute based providers

Like with interfaces, attribute provider works almost the same way. The only difference is that the source type is the attribute type and the trigger to include the behavior is decoration of the inner class by this attribute, for e.g. the ReprocessAttribute and ReprocessBehavior is implemented this way.

Executing behavior pipeline*

...

Compiling tiny proxy for behaviors

...

You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.