ÎÒÃÇÖªµÀÓ¦ÓÃÔÚÄ¿±êÀàÐÍ»òÕßÆä·½·¨ÉϵÄInterceptorÄܹ»ÉúЧ£¬ÒªÇó·½·¨µ÷ÓÃÕë¶ÔµÄÊÇ·â×°Ä¿±ê¶ÔÏóµÄProxy¶ÔÏ󣬻»¾ä»°ËµÎÒÃÇÏ£ÍûÌṩµÄ¶ÔÏóÊÇÒ»¸öProxy¶ø²»ÊÇÄ¿±ê¶ÔÏó¡£³ý´ËÖ®Í⣬ÎÒÃÇÔÚÉÏÃæµÄÉè¼ÆÄ¿±êÒѾÌáµ½¹ý£¬ÎÒÃÇÏ£ÍûÕâ¸öAOP¿ò¼ÜÄܹ»Óë.NET CoreµÄDependency Injection¿ò¼Ü½øÐÐÎ޷켯³É£¬ËùÒÔÏÖÔÚµÄÎÊÌâ±ä³ÉÁË£ºÈçºÎÈÃDependency InjectionµÄServiceProviderÌṩµÄÊÇProxy¶ÔÏ󣬶ø²»ÊÇÄ¿±ê¶ÔÏó¡£ÎÒÌṩµÄÁ½ÖÖ·½°¸À´½â¾öÕâ¸öÎÊÌ⣬½ÓÏÂÀ´ÎÒÃÇͨ¹ýÒ»¸öASP.NET Core MVCÓ¦ÓÃÀ´¾ÙÀý˵Ã÷¡£
ΪÁËÄܹ»Ê¹ÓÃÉÏÃæÌṩµÄCacheInterceptor²¢ÇÒÄܹ»ÒÔºÜÖ±¹ÛµÄ·½Ê½¸ÐÊܵ½»º´æµÄ´æÔÚ£¬ÎÒ¶¨ÒåÁËÈçÏÂÕâ¸ö±íʾϵͳʱÖÓµÄISystemClock½Ó¿ÚºÍ¾ßÌåʵÏÖÀàÐÍSystemClock¡£´ÓÈçϵĴúÂëƬ¶Î¿ÉÒÔ¿´³ö£¬GetCurrentTime·½·¨×ÜÊÇ·µ»ØʵʱµÄʱ¼ä£¬µ«ÊÇÓÉÓÚÓ¦ÓÃÁËCaheReturnValueAttribute£¬Èç¹ûCacheInterceptorÉúЧ£¬·µ»ØµÄʱ¼äÔÚ»º´æ¹ýÆÚ֮ǰ×ÜÊÇÏàͬµÄ¡£
class SystomClock : ISystomClock 7: { 8: [CacheReturnValue] 9: public DateTime GetCurrentTime() 10: { 11: return DateTime.UtcNow; 12: } 13: }
ÎÒÃÇÔÚHomeControllerÖÐÒÔ¹¹ÔìÆ÷×¢ÈëµÄ·½Ê½À´Ê¹ÓÃISystemClock¡£ÔÚĬÈÏÇé¿öÏ£¬Èç¹ûÎÒÃÇ×¢ÈëµÄÀàÐÍISystemClock½Ó¿Ú£¬ÄÇôºÁÎÞÒÉÎÊ£¬ÄÇôGetCurrentTime·½·¨µ÷ÓõľÍÊÇSystemClock¶ÔÏó±¾Éí£¬ËùÒÔ¸ù±¾²»¿ÉÄÜÆðµ½»º´æµÄ×÷Óá£ËùÒÔÎÒÃǽ«×¢ÈëÀàÐÍÌæ»»³ÉIInterceptable<ISystomClock>£¬ºóÕßµÄProxyÊôÐÔ½«»á·µ»ØÎÒÃÇÏ£ÍûµÄProxy¶ÔÏó¡£
1: public class HomeController : Controller 2: { 3: private readonly ISystomClock _clock; 4: public HomeController(IInterceptable<ISystomClock> clockAccessor) 5: { 6: _clock = clockAccessor.Proxy; 7: } 8: 9: [HttpGet("http://www.cnblogs.com/")] 10: public async Task Index() 11: { 12: this.Response.ContentType = "text/html"; 13: await this.Response.WriteAsync("<html><body><ul>"); 14: for (int i = 0; i < 5; i++) 15: { 16: await this.Response.WriteAsync($"<li>{_clock.GetCurrentTime()}({DateTime.UtcNow})</li>"); 17: await Task.Delay(1000); 18: } 19: await this.Response.WriteAsync("</ul><body></html>"); 20: } 21: }
µ±È»ÎÒÃÇÐèҪע²áDora.InterceptionһЩ±ØÐëµÄ·þÎñ£¬ÕâЩ·þÎñ²ÉÓÃÈçϵÄÐÎʽͨ¹ýµ÷ÓÃÀ©Õ¹·½·¨AddInterceptionÀ´ÊµÏÖ¡£
1: public class Startup 2: { 3: public void ConfigureServices(IServiceCollection services) 4: { 5: services 6: .AddScoped<ISystomClock, SystomClock>() 7: .AddInterception(builder=>builder.SetDynamicProxyFactory()) 8: .AddMvc(); 9: } 10: public void Configure(IApplicationBuilder app) 11: { 12: app.UseMvc(); 13: } 14: }
ËäÈ»IInterceptable<T>Äܹ»½â¾öProxyµÄÌṩÎÊÌ⣬µ«ÊÇÕâÖÖ±à³ÌģʽÆäʵÊǺܲ»ºÃµÄ¡£ÀíÏëµÄ±à³ÌģʽӦ¸ÃÊÇ£ºÒÀÀµÄ³¸ö·þÎñ¾Í×¢Èë¶ÔÓ¦µÄ·þÎñ½Ó¿Ú¾Í¿ÉÒÔ¡£Õâ¸öÎÊÌâÆäʵҲºÃ½â¾ö£¬ÎÒÃÇÊ×ÏȽ«HomeController»¹Ô³ÉµäÐ͵ıà³Ìģʽ£º
1: public class HomeController : Controller 2: { 3: private readonly ISystomClock _clock; 4: public HomeController(ISystomClock clock) 5: { 6: _clock = clock; 7: } 8: 9: [HttpGet("http://www.cnblogs.com/")] 10: public async Task Index() 11: { 12: this.Response.ContentType = "text/html"; 13: await this.Response.WriteAsync("<html><body><ul>"); 14: for (int i = 0; i < 5; i++) 15: { 16: await this.Response.WriteAsync($"<li>{_clock.GetCurrentTime()}({DateTime.UtcNow})</li>"); 17: await Task.Delay(1000); 18: } 19: await this.Response.WriteAsync("</ul><body></html>"); 20: } 21: }
¡¡