Asp Core Automating Cache with Aspect Programming (Autofac + Dynamic Proxy)
--
Aspect-Oriented Programming
Aspect-Oriented Programming (AOP) is a programming paradigm that complements Object-Oriented Programming (OOP) by separating concerns of a software application to improve modularization. The separation of concerns (SoC) aims for making software easier to maintain by grouping features and behavior into manageable parts which all have a specific purpose and business to take care of.
These behaviors that are not central to the business logic can be added without cluttering your code.
You’ll be using Autofac and DynamicProxy from the Castle project for the examples, below. download source in Github repository. We automatically cache our method using interception.
In this method, MessagePack with lz4 compression algorithm is used to increase the speed and reduce the cache volume.
1-New Project
new project asp core empty template.
2-Instal Nuget Package
Autofac.Extensions.DependencyInjection
3-Startup.cs
add AddDistributedMemoryCache for cache provider. You can have your own provider, like Redis or SQL server distributed.
services.AddDistributedMemoryCache();
Autofac Add Registry to Services That Have Been Already Added.
var builder = new ContainerBuilder();builder.Populate(services);
Add interceptor
builder.RegisterType<CacheInterceptor>();
Add service
builder.RegisterType<TestService>().As<ITestService>().InstancePerLifetimeScope().EnableInterfaceInterceptors().InterceptedBy(typeof(CacheInterceptor));
build autofac container
AutofacContainer = builder.Build();// this will be used as the service-provider for the application!return new AutofacServiceProvider(AutofacContainer);
4.Add CacheMethodAttribute
5.Add Extension Methods
6-Add CacheInterceptor
7-Add Service
There are a few points to using
- You can use the HTTP cache next to this type of cache
-You can also serialize the message pack using the message pack, which has a good return
- Self-processing is a costly process, but the point is that it is far less expensive than doing it yourself, such as connecting to a database or requesting HTTP.
-The messagepack algorithm serials very, very fast
-The lz4 algorithm compresses excellently