AOP through Unity interceptors - Compression

Today we are going to compress our data. We will still use AOP through Unity.

The scenario is the following: we have a class generating a huge set of data (in our example, data structure is string). we don't want it to be kept in memory, because we will use it later, or not often. So one solution could be to compress this data & uncompress it once we will really need it.
public interface IBigDataRepo
    {
        string GetData();
    }
 public class BigDataRepo : IBigDataRepo
    {
        public string GetData()
        {
            return new string('X', 100000);
        }
    }
We are going to use is this way:

static void Main(string[] args)
        {
            using (var container = new UnityContainer())
            {
                container.AddNewExtension<Interception>();

                // Register
                container.RegisterType<IBigDataRepo, BigDataRepo>(
                    new Interceptor<InterfaceInterceptor>(),
                    new InterceptionBehavior<CompressionInterceptionBehavior>());

                // Resolve
                IBigDataRepo bigDataRepo = container.Resolve<IBigDataRepo>();

                // Call
                string compressedData = bigDataRepo.GetData();

                Console.WriteLine(compressedData.Length);

                Console.WriteLine("END");
                Console.ReadLine();

            }

        }
That's  all. Now, let's see how the CompressionInterceptionBehavior is made.

public class CompressionInterceptionBehavior : IInterceptionBehavior
    {
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            var result = getNext()(input, getNext);

            return input.CreateMethodReturn(Compress(result.ReturnValue));
        }

        private object Compress(object stringToCompress)
        {
            byte[] text = Encoding.ASCII.GetBytes(stringToCompress.ToString());
            using (MemoryStream memory = new MemoryStream())
            {
                using (GZipStream gzip = new GZipStream(memory, CompressionMode.Compress, true))
                {
                    gzip.Write(text, 0, text.Length);
                }
                 return Encoding.ASCII.GetString(memory.ToArray());
            }
        }

        public IEnumerable<Type> GetRequiredInterfaces()
        {
            return Type.EmptyTypes;
        }

        public bool WillExecute { get { return true; } }
    }

Simple enough. The most complicated part is the compression part :).

Comments

Popular posts from this blog

EMGU with Xamarin Forms guide [part 1]

[Xamarin Forms] Custom bottom bordered entry (iOS & Android)

Xamarin.Forms device unique ID...