Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Delegate based adapter to ISerializer #5

Open
bruno-garcia opened this issue Dec 3, 2017 · 0 comments
Open

Delegate based adapter to ISerializer #5

bruno-garcia opened this issue Dec 3, 2017 · 0 comments

Comments

@bruno-garcia
Copy link
Collaborator

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant