How to trigger the custom attribute method before and after execution of method c#

1.3k Views Asked by At

I want to design a automated way for saving/retrieving the data from cache. This is how I want to design the architecture for it.

There would be 2 class libraries

DB.DataAccess -> This layer will execute the sp/quires by using ado.net to access the data from database

DB.DataDistributor -> This will be a middle tier between db and presentation layer call the DB.DataAccess to get the data

in DB.DataDistributor I want to automate the data caching like this way by using custom attribute.

namespace DB.DataDistributor
{
    public class MessageManager
    {


        [CachDataAttribute(CacheKey = CacheKeys.Message, CacheDataType = typeof(List<Message>))]
        public List<Message> GetMessages()
        {
            DB.DataAccess.MesssageManager msgManager = null;
            try
            {
                msgManager = new DB.DataAccess.MesssageManager();
                var messages = msgManager.GetMessages();
                return messages;
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                msgManager = null;
            }
        }


    }
}

namespace DB.DataDistributor
{
    [AttributeUsage(AttributeTargets.Method)]
    internal class DataCachingFilterAttribute : Attribute
    {
        public CacheKeys CacheKey { get; set; }
        public Type CacheDataType { get; set; }

        public void SetCache()
        {
            //this method should call after execution of method where DataCachingFilterAttribute has attached 
        }

        public void GetCache()
        {
            //this method should call before execution of method where DataCachingFilterAttribute has attached
            //here I will check if data available in cache then will return data from cache and do not call the achtual method 
        }
    }

    public enum CacheKeys
    {
        Message
    }
}
  • Whenever presentation layer calls GetMessages method of DB.DataDistributor.MessageManager system should execute the GetCache() method of DataCachingFilterAttribute class if data found in cache then the actual method GetMessages should not be executed and data return directally from cache else called the GetMessages and return the data from there.

  • Right after result returned from GetMessages the SetCache method of DataCachingFilterAttribute should call to set the result in cache.

This is my thought to automate the data caching but I am not getting how to trigger the DataCachingFilterAttribute methods before and after GetMessages method execution.

If anyone has any idea or other good approach to automate the caching please share.

0

There are 0 best solutions below