Skip to content

Delegate based adapter to ISerializer #5

@bruno-garcia

Description

@bruno-garcia

Build a strategy-based implementation of ISerializer. In the lines of DelegatedSerializer : ISerializer
It's to be built at the root package Greentube.Serialization.

This will allow consumer to easily plug their implementation.

Something like as:

new DelegatedSerializer(FutureSerializer.Serialize, FutureSerializer.Deserialize);

The DependencyInjection package would expose an easy way in, like: .AddDelegated(a,b).

Proposed API:

    /// <summary>
    /// Delegates the serialization calls to a strategy
    /// </summary>
    /// <inheritdoc />
    public class DelegatedSerializer : ISerializer
    {
        private readonly Func<Type, byte[], object> _deserialize;
        private readonly Func<Type, object, byte[]> _serialize;

        /// <inheritdoc />
        public DelegatedSerializer(
            Func<Type, byte[], object> deserialize, 
            Func<Type, object, byte[]> serialize)
        {
            _deserialize = deserialize ?? throw new ArgumentNullException(nameof(deserialize));
            _serialize = serialize ?? throw new ArgumentNullException(nameof(serialize));
        }

        /// <inheritdoc />
        public byte[] Serialize<T>(T @object) => _serialize(typeof(T), @object);

        /// <inheritdoc />
        public object Deserialize(Type type, byte[] bytes) => _deserialize(type, bytes);
    }

The reason I proposed providing typeof(T) instead of relying on @object.GetType() on the serialization func is that the generic argument provided could be different than the actual instance. Therefore the information should be passed to the strategy.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions