├── .gitattributes ├── .gitignore ├── API ├── API.csproj ├── Controllers │ └── CustomersController.cs ├── Program.cs ├── Properties │ └── launchSettings.json ├── Startup.cs ├── appsettings.Development.json └── appsettings.json ├── Core ├── Abstractions │ ├── ICacheableMediatrQuery.cs │ └── ICustomerService.cs ├── Behaviors │ └── CachingBehavior.cs ├── Core.csproj ├── Entities │ └── Customer.cs ├── Extensions │ └── ServiceCollectionExtensions.cs ├── Features │ └── Customers │ │ ├── GetCustomer │ │ └── GetCustomerQuery.cs │ │ └── GetCustomerList │ │ └── GetCustomerListQuery.cs └── Settings │ └── CacheSettings.cs ├── Infrastructure ├── CustomerService.cs └── Infrastructure.csproj ├── MediatRReponseCaching.sln └── README.md /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Oo]ut/ 33 | [Ll]og/ 34 | [Ll]ogs/ 35 | 36 | # Visual Studio 2015/2017 cache/options directory 37 | .vs/ 38 | # Uncomment if you have tasks that create the project's static files in wwwroot 39 | #wwwroot/ 40 | 41 | # Visual Studio 2017 auto generated files 42 | Generated\ Files/ 43 | 44 | # MSTest test Results 45 | [Tt]est[Rr]esult*/ 46 | [Bb]uild[Ll]og.* 47 | 48 | # NUnit 49 | *.VisualState.xml 50 | TestResult.xml 51 | nunit-*.xml 52 | 53 | # Build Results of an ATL Project 54 | [Dd]ebugPS/ 55 | [Rr]eleasePS/ 56 | dlldata.c 57 | 58 | # Benchmark Results 59 | BenchmarkDotNet.Artifacts/ 60 | 61 | # .NET Core 62 | project.lock.json 63 | project.fragment.lock.json 64 | artifacts/ 65 | 66 | # ASP.NET Scaffolding 67 | ScaffoldingReadMe.txt 68 | 69 | # StyleCop 70 | StyleCopReport.xml 71 | 72 | # Files built by Visual Studio 73 | *_i.c 74 | *_p.c 75 | *_h.h 76 | *.ilk 77 | *.meta 78 | *.obj 79 | *.iobj 80 | *.pch 81 | *.pdb 82 | *.ipdb 83 | *.pgc 84 | *.pgd 85 | *.rsp 86 | *.sbr 87 | *.tlb 88 | *.tli 89 | *.tlh 90 | *.tmp 91 | *.tmp_proj 92 | *_wpftmp.csproj 93 | *.log 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio LightSwitch build output 298 | **/*.HTMLClient/GeneratedArtifacts 299 | **/*.DesktopClient/GeneratedArtifacts 300 | **/*.DesktopClient/ModelManifest.xml 301 | **/*.Server/GeneratedArtifacts 302 | **/*.Server/ModelManifest.xml 303 | _Pvt_Extensions 304 | 305 | # Paket dependency manager 306 | .paket/paket.exe 307 | paket-files/ 308 | 309 | # FAKE - F# Make 310 | .fake/ 311 | 312 | # CodeRush personal settings 313 | .cr/personal 314 | 315 | # Python Tools for Visual Studio (PTVS) 316 | __pycache__/ 317 | *.pyc 318 | 319 | # Cake - Uncomment if you are using it 320 | # tools/** 321 | # !tools/packages.config 322 | 323 | # Tabs Studio 324 | *.tss 325 | 326 | # Telerik's JustMock configuration file 327 | *.jmconfig 328 | 329 | # BizTalk build output 330 | *.btp.cs 331 | *.btm.cs 332 | *.odx.cs 333 | *.xsd.cs 334 | 335 | # OpenCover UI analysis results 336 | OpenCover/ 337 | 338 | # Azure Stream Analytics local run output 339 | ASALocalRun/ 340 | 341 | # MSBuild Binary and Structured Log 342 | *.binlog 343 | 344 | # NVidia Nsight GPU debugger configuration file 345 | *.nvuser 346 | 347 | # MFractors (Xamarin productivity tool) working folder 348 | .mfractor/ 349 | 350 | # Local History for Visual Studio 351 | .localhistory/ 352 | 353 | # BeatPulse healthcheck temp database 354 | healthchecksdb 355 | 356 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 357 | MigrationBackup/ 358 | 359 | # Ionide (cross platform F# VS Code tools) working folder 360 | .ionide/ 361 | 362 | # Fody - auto-generated XML schema 363 | FodyWeavers.xsd -------------------------------------------------------------------------------- /API/API.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /API/Controllers/CustomersController.cs: -------------------------------------------------------------------------------- 1 | using Core.Features.Customers.GetCustomer; 2 | using Core.Features.Customers.GetCustomerList; 3 | using MediatR; 4 | using Microsoft.AspNetCore.Mvc; 5 | using System.Threading.Tasks; 6 | 7 | namespace API.Controllers 8 | { 9 | [Route("api/[controller]")] 10 | [ApiController] 11 | public class CustomersController : ControllerBase 12 | { 13 | private readonly IMediator _mediator; 14 | 15 | public CustomersController(IMediator mediator) 16 | { 17 | _mediator = mediator; 18 | } 19 | 20 | [HttpGet("{id}")] 21 | public async Task GetCustomer(int id) 22 | { 23 | var customer = await _mediator.Send(new GetCustomerQuery { Id = id, BypassCache = false }); 24 | return Ok(customer); 25 | } 26 | 27 | [HttpGet] 28 | public async Task GetCustomerList() 29 | { 30 | var customers = await _mediator.Send(new GetCustomerListQuery { BypassCache = false }); 31 | return Ok(customers); 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /API/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Hosting; 2 | using Microsoft.Extensions.Hosting; 3 | 4 | namespace API 5 | { 6 | public class Program 7 | { 8 | public static void Main(string[] args) 9 | { 10 | CreateHostBuilder(args).Build().Run(); 11 | } 12 | 13 | public static IHostBuilder CreateHostBuilder(string[] args) => 14 | Host.CreateDefaultBuilder(args) 15 | .ConfigureWebHostDefaults(webBuilder => 16 | { 17 | webBuilder.UseStartup(); 18 | }); 19 | } 20 | } -------------------------------------------------------------------------------- /API/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:22894", 8 | "sslPort": 44333 9 | } 10 | }, 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchBrowser": true, 15 | "launchUrl": "swagger", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | } 19 | }, 20 | "MediatRReponseCaching": { 21 | "commandName": "Project", 22 | "dotnetRunMessages": "true", 23 | "launchBrowser": true, 24 | "launchUrl": "swagger", 25 | "applicationUrl": "https://localhost:5001;http://localhost:5000", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /API/Startup.cs: -------------------------------------------------------------------------------- 1 | using Core.Abstractions; 2 | using Core.Extensions; 3 | using Core.Settings; 4 | using Infrastructure; 5 | using Microsoft.AspNetCore.Builder; 6 | using Microsoft.AspNetCore.Hosting; 7 | using Microsoft.Extensions.Configuration; 8 | using Microsoft.Extensions.DependencyInjection; 9 | using Microsoft.Extensions.Hosting; 10 | using Microsoft.OpenApi.Models; 11 | 12 | namespace API 13 | { 14 | public class Startup 15 | { 16 | public Startup(IConfiguration configuration) 17 | { 18 | config = configuration; 19 | } 20 | 21 | public IConfiguration config { get; } 22 | 23 | // This method gets called by the runtime. Use this method to add services to the container. 24 | public void ConfigureServices(IServiceCollection services) 25 | { 26 | services.AddDistributedMemoryCache(); 27 | services.AddCoreLayer(config); 28 | services.AddTransient(); 29 | services.Configure(config.GetSection("CacheSettings")); 30 | services.AddControllers(); 31 | services.AddSwaggerGen(c => 32 | { 33 | c.SwaggerDoc("v1", new OpenApiInfo { Title = "MediatRReponseCaching", Version = "v1" }); 34 | }); 35 | } 36 | 37 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 38 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 39 | { 40 | if (env.IsDevelopment()) 41 | { 42 | app.UseDeveloperExceptionPage(); 43 | app.UseSwagger(); 44 | app.UseSwaggerUI(c => { c.DisplayRequestDuration(); c.SwaggerEndpoint("/swagger/v1/swagger.json", "MediatRReponseCaching v1"); }); 45 | } 46 | 47 | app.UseHttpsRedirection(); 48 | 49 | app.UseRouting(); 50 | 51 | app.UseAuthorization(); 52 | 53 | app.UseEndpoints(endpoints => 54 | { 55 | endpoints.MapControllers(); 56 | }); 57 | } 58 | } 59 | } -------------------------------------------------------------------------------- /API/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | } 9 | } -------------------------------------------------------------------------------- /API/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "AllowedHosts": "*", 10 | "CacheSettings": { 11 | "SlidingExpiration": 2 12 | } 13 | } -------------------------------------------------------------------------------- /Core/Abstractions/ICacheableMediatrQuery.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Core.Abstractions 4 | { 5 | public interface ICacheableMediatrQuery 6 | { 7 | bool BypassCache { get; } 8 | string CacheKey { get; } 9 | TimeSpan? SlidingExpiration { get; } 10 | } 11 | } -------------------------------------------------------------------------------- /Core/Abstractions/ICustomerService.cs: -------------------------------------------------------------------------------- 1 | using Core.Entities; 2 | using System.Collections.Generic; 3 | 4 | namespace Core.Abstractions 5 | { 6 | public interface ICustomerService 7 | { 8 | IEnumerable GetCustomerList(); 9 | 10 | Customer GetCustomer(int id); 11 | } 12 | } -------------------------------------------------------------------------------- /Core/Behaviors/CachingBehavior.cs: -------------------------------------------------------------------------------- 1 | using Core.Abstractions; 2 | using Core.Settings; 3 | using MediatR; 4 | using Microsoft.Extensions.Caching.Distributed; 5 | using Microsoft.Extensions.Logging; 6 | using Microsoft.Extensions.Options; 7 | using Newtonsoft.Json; 8 | using System; 9 | using System.Text; 10 | using System.Threading; 11 | using System.Threading.Tasks; 12 | 13 | namespace Core.Behaviors 14 | { 15 | public class CachingBehavior : IPipelineBehavior where TRequest : notnull 16 | { 17 | private readonly IDistributedCache _cache; 18 | private readonly ILogger _logger; 19 | private readonly CacheSettings _settings; 20 | 21 | public CachingBehavior(IDistributedCache cache, ILogger logger, IOptions settings) 22 | { 23 | _cache = cache ?? throw new ArgumentNullException(nameof(cache)); 24 | _logger = logger ?? throw new ArgumentNullException(nameof(logger)); 25 | _settings = settings.Value; 26 | } 27 | 28 | public async Task Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate next) 29 | { 30 | if (request is ICacheableMediatrQuery cacheableQuery) 31 | { 32 | TResponse response; 33 | if (cacheableQuery.BypassCache) return await next(); 34 | async Task GetResponseAndAddToCache() 35 | { 36 | response = await next(); 37 | var slidingExpiration = cacheableQuery.SlidingExpiration == null ? TimeSpan.FromHours(_settings.SlidingExpiration) : cacheableQuery.SlidingExpiration; 38 | var options = new DistributedCacheEntryOptions { SlidingExpiration = slidingExpiration }; 39 | var serializedData = Encoding.Default.GetBytes(JsonConvert.SerializeObject(response)); 40 | await _cache.SetAsync(cacheableQuery.CacheKey, serializedData, options, cancellationToken); 41 | return response; 42 | } 43 | 44 | var cachedResponse = await _cache.GetAsync(cacheableQuery.CacheKey, cancellationToken); 45 | if (cachedResponse != null) 46 | { 47 | response = JsonConvert.DeserializeObject(Encoding.Default.GetString(cachedResponse)); 48 | _logger.LogInformation($"Fetched from Cache -> '{cacheableQuery.CacheKey}'."); 49 | } 50 | else 51 | { 52 | response = await GetResponseAndAddToCache(); 53 | _logger.LogInformation($"Added to Cache -> '{cacheableQuery.CacheKey}'."); 54 | } 55 | 56 | return response; 57 | } 58 | else 59 | { 60 | return await next(); 61 | } 62 | } 63 | } 64 | } -------------------------------------------------------------------------------- /Core/Core.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net5.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /Core/Entities/Customer.cs: -------------------------------------------------------------------------------- 1 | namespace Core.Entities 2 | { 3 | public class Customer 4 | { 5 | public int Id { get; set; } 6 | public string FirstName { get; set; } 7 | public string LastName { get; set; } 8 | public string Contact { get; set; } 9 | public string Email { get; set; } 10 | } 11 | } -------------------------------------------------------------------------------- /Core/Extensions/ServiceCollectionExtensions.cs: -------------------------------------------------------------------------------- 1 | using Core.Behaviors; 2 | using MediatR; 3 | using Microsoft.Extensions.Configuration; 4 | using Microsoft.Extensions.DependencyInjection; 5 | using System.Reflection; 6 | 7 | namespace Core.Extensions 8 | { 9 | public static class ServiceCollectionExtensions 10 | { 11 | public static IServiceCollection AddCoreLayer(this IServiceCollection services, IConfiguration config) 12 | { 13 | services.AddMediatR(Assembly.GetExecutingAssembly()); 14 | services.AddTransient(typeof(IPipelineBehavior<,>), typeof(CachingBehavior<,>)); 15 | 16 | return services; 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /Core/Features/Customers/GetCustomer/GetCustomerQuery.cs: -------------------------------------------------------------------------------- 1 | using Core.Abstractions; 2 | using Core.Entities; 3 | using MediatR; 4 | using System; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | 8 | namespace Core.Features.Customers.GetCustomer 9 | { 10 | public class GetCustomerQuery : IRequest, ICacheableMediatrQuery 11 | { 12 | public int Id { get; set; } 13 | public bool BypassCache { get; set; } 14 | public string CacheKey => $"Customer-{Id}"; 15 | public TimeSpan? SlidingExpiration { get; set; } 16 | } 17 | 18 | internal class GetCustomerQueryHandler : IRequestHandler 19 | { 20 | private readonly ICustomerService customerService; 21 | 22 | public GetCustomerQueryHandler(ICustomerService customerService) 23 | { 24 | this.customerService = customerService; 25 | } 26 | 27 | public async Task Handle(GetCustomerQuery request, CancellationToken cancellationToken) 28 | { 29 | var cutomer = customerService.GetCustomer(request.Id); 30 | return cutomer; 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /Core/Features/Customers/GetCustomerList/GetCustomerListQuery.cs: -------------------------------------------------------------------------------- 1 | using Core.Abstractions; 2 | using Core.Entities; 3 | using MediatR; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Threading; 8 | using System.Threading.Tasks; 9 | 10 | namespace Core.Features.Customers.GetCustomerList 11 | { 12 | public class GetCustomerListQuery : IRequest>, ICacheableMediatrQuery 13 | { 14 | public int Id { get; set; } 15 | public bool BypassCache { get; set; } 16 | public string CacheKey => $"CustomerList"; 17 | public TimeSpan? SlidingExpiration { get; set; } 18 | } 19 | 20 | internal class GetCustomerListQueryHandler : IRequestHandler> 21 | { 22 | private readonly ICustomerService customerService; 23 | 24 | public GetCustomerListQueryHandler(ICustomerService customerService) 25 | { 26 | this.customerService = customerService; 27 | } 28 | 29 | public async Task> Handle(GetCustomerListQuery request, CancellationToken cancellationToken) 30 | { 31 | var cutomers = customerService.GetCustomerList(); 32 | return cutomers.ToList(); 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /Core/Settings/CacheSettings.cs: -------------------------------------------------------------------------------- 1 | namespace Core.Settings 2 | { 3 | public class CacheSettings 4 | { 5 | public int SlidingExpiration { get; set; } 6 | } 7 | } -------------------------------------------------------------------------------- /Infrastructure/CustomerService.cs: -------------------------------------------------------------------------------- 1 | using Core.Abstractions; 2 | using Core.Entities; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Threading; 6 | 7 | namespace Infrastructure 8 | { 9 | public class CustomerService : ICustomerService 10 | { 11 | public static IEnumerable Customers => new List 12 | { 13 | new Customer{ Id = 1, Contact = "123456789", Email="john@gmail.com", FirstName="John", LastName = "Doe"}, 14 | new Customer{ Id = 2, Contact = "564514501", Email="ray@gmail.com", FirstName="Ray", LastName = "Doe"}, 15 | new Customer{ Id = 3, Contact = "141510217", Email="smith@gmail.com", FirstName="Smith", LastName = "Doe"}, 16 | new Customer{ Id = 4, Contact = "254112152", Email="mukesh@gmail.com", FirstName="Mukesh", LastName = "Murugan"}, 17 | new Customer{ Id = 5, Contact = "125452338", Email="helen@gmail.com", FirstName="Helen", LastName = "Doe"}, 18 | new Customer{ Id = 6, Contact = "985171215", Email="jack@gmail.com", FirstName="Jack", LastName = "Doe"}, 19 | new Customer{ Id = 7, Contact = "653107410", Email="marc@gmail.com", FirstName="Marc", LastName = "Doe"}, 20 | new Customer{ Id = 8, Contact = "165357410", Email="tim@gmail.com", FirstName="Tim", LastName = "Doe"}, 21 | new Customer{ Id = 9, Contact = "012543413", Email="jimmy@gmail.com", FirstName="Jimmy", LastName = "Doe"}, 22 | new Customer{ Id = 10, Contact = "124633892", Email="dany@gmail.com", FirstName="Dany", LastName = "Doe"}, 23 | }; 24 | 25 | public Customer GetCustomer(int id) 26 | { 27 | //Assume Database Response takes 1000 ms 28 | Thread.Sleep(1000); 29 | return Customers.Where(c => c.Id == id).FirstOrDefault(); 30 | } 31 | 32 | public IEnumerable GetCustomerList() 33 | { 34 | //Assume Database Response takes 3000 ms 35 | Thread.Sleep(3000); 36 | return Customers; 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /Infrastructure/Infrastructure.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /MediatRReponseCaching.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.31313.79 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "API", "API\API.csproj", "{31F263D6-65C2-4016-B1AA-3531CFEDC9C2}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Core", "Core\Core.csproj", "{9911A50C-5365-4F68-BBA0-CB2B9EBF42AA}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Infrastructure", "Infrastructure\Infrastructure.csproj", "{3BF4B9EF-F2E4-4069-9EC7-08CF11279376}" 11 | EndProject 12 | Global 13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 14 | Debug|Any CPU = Debug|Any CPU 15 | Release|Any CPU = Release|Any CPU 16 | EndGlobalSection 17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 18 | {31F263D6-65C2-4016-B1AA-3531CFEDC9C2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 19 | {31F263D6-65C2-4016-B1AA-3531CFEDC9C2}.Debug|Any CPU.Build.0 = Debug|Any CPU 20 | {31F263D6-65C2-4016-B1AA-3531CFEDC9C2}.Release|Any CPU.ActiveCfg = Release|Any CPU 21 | {31F263D6-65C2-4016-B1AA-3531CFEDC9C2}.Release|Any CPU.Build.0 = Release|Any CPU 22 | {9911A50C-5365-4F68-BBA0-CB2B9EBF42AA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {9911A50C-5365-4F68-BBA0-CB2B9EBF42AA}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {9911A50C-5365-4F68-BBA0-CB2B9EBF42AA}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {9911A50C-5365-4F68-BBA0-CB2B9EBF42AA}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {3BF4B9EF-F2E4-4069-9EC7-08CF11279376}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {3BF4B9EF-F2E4-4069-9EC7-08CF11279376}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {3BF4B9EF-F2E4-4069-9EC7-08CF11279376}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {3BF4B9EF-F2E4-4069-9EC7-08CF11279376}.Release|Any CPU.Build.0 = Release|Any CPU 30 | EndGlobalSection 31 | GlobalSection(SolutionProperties) = preSolution 32 | HideSolutionNode = FALSE 33 | EndGlobalSection 34 | GlobalSection(ExtensibilityGlobals) = postSolution 35 | SolutionGuid = {92CF370D-08D6-4803-97D8-00A4FF562E6E} 36 | EndGlobalSection 37 | EndGlobal 38 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Response Caching with MediatR in ASP.NET Core 2 | 3 | In this article, we are going to implement Response Caching with MediatR in ASP.NET Core using its awesome Pipeline Behaviours. This means that every response that is sent out of your application (API) will be cached with a very simple implementation. I have written a couple of articles about MediatR and why it’s one of the MUST USE libraries for .NET devs. This library simplifies your Application to an extent yet gives you complete control. 4 | 5 | Topics Covered 6 | 1. What’s Response Caching with MediatR? 7 | 2. What we will build? 8 | 3. Getting started with Caching with MediatR in ASP.NET Core 9 | 4. Adding the ICacheableMediatrQuery interface 10 | 5. Cache Setting – appSettings 11 | 6. Implementing the Caching Behavior – Explained 12 | 7. Building the CQRS Handlers 13 | 8. Testing with Swagger 14 | 15 | Read the entire article: https://codewithmukesh.com/blog/caching-with-mediatr-in-aspnet-core/ 16 | 17 | Buy Me A Coffee 18 | 19 | --------------------------------------------------------------------------------