5588葡京线路桂林山水&米粉

月亮山

三、扩展点

光这等同变更象鼻,巧夺天工,浑然天成,煞是好看。

    
Controller类型、ControllerFactory类型和ControllerBuilder类型,他们之间的涉及可以描述为:ControllerBuilder是面向客户的,或者说是程序员和ASP.NET
MVC框架中的桥梁。我们经过ControllerBuilder类型的SetControllerFactory方法把我们打定义之ControllerFactory类型实例注册到ASP.NET
MVC框架中,ControllerFactory类型用于管理Controller类型实例,其实为便是说ControllerFactory类型就是ASP.NET
MVC框架中的一个扩展点。

新近螺蛳粉好像死红,大有网红美食的势。

同一、“路由于网”和“激活系统”是怎干起来的

肉麻而你。

      
DefaultControllerFactory会先经“MVC-ControllerTypeCache.xml”文件来加载Controller的项目,如果没有找到有效的数目才见面由此调用BuildManager的静态方法GetReferencedAssemblies获取到网所利用到的备程序集,然后对每个程序集通过反射的艺术取得有实现了IController接口的路,并XML文件之款式缓存起来,缓存的文件称就是是“MVC-ControllerTypeCache.xml”。然后我们将Controller的称与命名空间作为匹配原则去摸索对应之Controller类型。当我们赢得了符合标准的真是的Controller类型后,DefaultControllerFactory对象通过反射的主意创造Controller类型的实例对象。解析逻辑不复杂,但是代码不少。首先我说明某些,把代码全部贴出不是为占据篇幅,而是以大家会看的再清楚,我管完整的源码贴出来,大家好仔细回味一下。

故而其好发售70首先门票,而白云山不得不发售5最先。因为它的固定完全不同,白云山凡是城里人公园,大众游览闲暇散步的所,与本国巨大市民公园差别不老。

  
MvcRouteHandler会给咱们一直回MvcHandler对象,这个目标用于拍卖要,包括激活Controler对象,代码最有说服力,这卖代码,上篇文章吧贴过,现在啊粘一下将,上代码:
  

自身当桂林底的确含义及之一日游,只来三三两两浅。

 
具体来说,该零件通过为RouteTable的静态属性Routes表示的路由表针对当前请实施路由于解析,如果生配合,就见面因路由对象Route来生成RouteData路由数对象,然后我们借助RouteData对象的RouteHandler属性获取想如果之HttpHandler对象。在默认情况下是RouteHandler属性所表示的目标是MvcRouteHandler。翠花,上代码:

咱俩同样增援女儿站于西街门口,手拉手拍照合影,背后是华灯初上古韵犹存的老街,脚踹着因为下雨而水光琉璃的大理石面。

    
这个艺术要是获得ControllerFactory实例,根据取得的ControllerFactory对象激活Controller对象,红色标的代码就是基本要点。说明一些,这个办法只有是概念了激活Controller算法的骨架,具体的实现在DefaultControllerFactory类型中。代码很简短,我深信不疑大家看的接头。

咱俩失去之时段以深秋。

其次、Controller的详细剖析过程

自身以知乎上见到一个报说,象鼻山景区其实挺粗,现在底入场券70头条,广州白云山凡她的10加倍,门票5第一。

     恢宏点三:扩展DependencyResolver

街道两旁是广式的低矮砖瓦房,如今已经变成商铺,摆放在各式旅游纪念品。装饰精美的咖啡店门口的铃时而响起,捧在烧咖啡的观光客穿门而过。

            
其实这为是一个扩展点,但是我们今天不扩大这里,因为IOC框架和此的关系不大,我们而壮大的凡亚深受保障之虚方法,方法签名如下:

银子岩于2000年对外开放,相对来说算是比较新的俏景点。银子岩属层楼式溶洞,洞内各色的钟乳石洁白晶莹,宛如夜空的银汉倾斜而生,闪烁出要银子般的光辉,故称“银子岩”。

 
于该档中含有了一个IControllerFactory类型成员字段,这个接口类型是怀有ControllerFactory都如必须实现的接口,否则就非叫Controller的厂子了。MvcRouteHandler类型有零星独构造函数,无参的尚未的说,另一个消传递一个IControllerFactory类型的参数,这个参数用于初始化MvcRouteHandler类型内部含有的花色也IControllerFactory的_controllerFactory字段。当我们组织MvcRouteHandler实例的时候,如果我们调用了随便参的构造函数,它见面当里边用ControllerBuilder.Current.GetControllerFactory()方法来赢得我们由此ControllerBuilder类型注册之IControllerFactory类型的实例,代码很明显:

银子岩

 1     public class UnityControllerFactory:DefaultControllerFactory
 2     {
 3         /// <summary>
 4         /// IOC的容器对象
 5         /// </summary>
 6         public IUnityContainer UnityContainer { get; private set; }
 7 
 8         /// <summary>
 9         /// 通过构造函数初始化IOC的容器对象
10         /// </summary>
11         /// <param name="unityContainer">传入的IOC容器对象</param>
12         public UnityControllerFactory(IUnityContainer unityContainer)
13         {
14             if (unityContainer != null)
15             {
16                 this.UnityContainer = unityContainer;
17             }
18             else
19             {
20                 throw new ArgumentNullException("容器对象不能为空!");
21             }
22         }
23 
24         /// <summary>
25         /// 
26         /// </summary>
27         /// <param name="requestContext"></param>
28         /// <param name="controllerType"></param>
29         /// <returns></returns>
30         protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
31         {
32             if (controllerType == null)
33             {
34                 return null;
35             }
36             return (IController)this.UnityContainer.Resolve(controllerType);
37         }
38     }

 1 /// <summary>Defines the methods that simplify service location and dependency resolution.</summary>
 2 public interface IDependencyResolver
 3 {
 4     /// <summary>Resolves singly registered services that support arbitrary object creation.</summary>
 5     /// <returns>The requested service or object.</returns>
 6     /// <param name="serviceType">The type of the requested service or object.</param>
 7     object GetService(Type serviceType);
 8 
 9     /// <summary>Resolves multiply registered services.</summary>
10     /// <returns>The requested services.</returns>
11     /// <param name="serviceType">The type of the requested services.</param>
12     IEnumerable<object> GetServices(Type serviceType);
13 }

emmmm…….

 1 [TypeForwardedFrom("System.Web.Routing, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=31bf3856ad364e35")]
 2 public class UrlRoutingModule : IHttpModule
 3 {
 4     private static readonly object _contextKey = new object();
 5 
 6     private static readonly object _requestDataKey = new object();
 7 
 8     private RouteCollection _routeCollection;
 9 
10     public RouteCollection RouteCollection
11     {
12         get
13         {
14             if (this._routeCollection == null)
15             {
16                 this._routeCollection = RouteTable.Routes;
17             }
18             return this._routeCollection;
19         }
20         set
21         {
22             this._routeCollection = value;
23         }
24     }
25 
26     protected virtual void Dispose()
27     {
28     }
29 
30     protected virtual void Init(HttpApplication application)
31     {
32         if (application.Context.Items[UrlRoutingModule._contextKey] != null)
33         {
34             return;
35         }
36         application.Context.Items[UrlRoutingModule._contextKey] = UrlRoutingModule._contextKey;
37         application.PostResolveRequestCache += new EventHandler(this.OnApplicationPostResolveRequestCache);
38     }
39 
40     private void OnApplicationPostResolveRequestCache(object sender, EventArgs e)
41     {
42         HttpContextBase context = new HttpContextWrapper(((HttpApplication)sender).Context);
43         this.PostResolveRequestCache(context);
44     }
45 
46     [Obsolete("This method is obsolete. Override the Init method to use the PostMapRequestHandler event.")]
47     public virtual void PostMapRequestHandler(HttpContextBase context)
48     {
49     }
50 
51     public virtual void PostResolveRequestCache(HttpContextBase context)
52     {
53         RouteData routeData = this.RouteCollection.GetRouteData(context);
54         if (routeData == null)
55         {
56             return;
57         }
58         IRouteHandler routeHandler = routeData.RouteHandler;
59         if (routeHandler == null)
60         {
61             throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, SR.GetString("UrlRoutingModule_NoRouteHandler"), new object[0]));
62         }
63         if (routeHandler is StopRoutingHandler)
64         {
65             return;
66         }
67         RequestContext requestContext = new RequestContext(context, routeData);
68         context.Request.RequestContext = requestContext;
69         IHttpHandler httpHandler = routeHandler.GetHttpHandler(requestContext);
70         if (httpHandler == null)
71         {
72             throw new InvalidOperationException(string.Format(CultureInfo.CurrentUICulture, SR.GetString("UrlRoutingModule_NoHttpHandler"), new object[]
73             {
74                 routeHandler.GetType()
75             }));
76         }
77         if (!(httpHandler is UrlAuthFailureHandler))
78         {
79             context.RemapHandler(httpHandler);
80             return;
81         }
82         if (FormsAuthenticationModule.FormsAuthRequired)
83         {
84             UrlAuthorizationModule.ReportUrlAuthorizationFailure(HttpContext.Current, this);
85             return;
86         }
87         throw new HttpException(401, SR.GetString("Assess_Denied_Description3"));
88     }
89 
90     void IHttpModule.Dispose()
91     {
92         this.Dispose();
93     }
94 
95     void IHttpModule.Init(HttpApplication application)
96     {
97         this.Init(application);
98     }
99 }

闻讯桂林还有马肉米粉,口感特别,美食一绝,在别处我还不曾来看过。但是就自己充分绝望而连无猎奇,现在反大不满没有品味一品。

 1 public class NinjectDependencyResolver : IDependencyResolver
 2     {
 3         public IKernel Kernel { get; private set; }
 4 
 5         public NinjectDependencyResolver()
 6         {
 7             this.Kernel = new StandardKernel();
 8         }
 9 
10         public void Register<TFrom, TTo>() where TTo : TFrom
11         {
12             this.Kernel.Bind<TFrom>().To<TTo>();
13         }
14 
15         public object GetService(Type serviceType)
16         {
17             return this.Kernel.TryGet(serviceType);
18         }
19 
20         public IEnumerable<object> GetServices(Type serviceType)
21         {
22             return this.Kernel.GetAll(serviceType);
23         }
24     }

————————————————————

            
DefaultControllerFactory类型在创造Controller实例的当儿,有少数独主意是可以扩展的,一个是深受保障的虚方法GetControllerType,我们得以定义自己之Controller类型的辨析方法的兑现,方法签名如下:

最后一章节,我们来言一讲话吃。

             
第一单非常容易想到的扩张点便是促成IControllerFactory接口,定义一个崭新的ControllerFactory类型。如果是这般,里面装有的效应的就算用全体重新实现,包括Controller类型的辨析、Controller实例的创建与销毁、也包罗会话状态作为模式之管住。这样的好处虽是咱们不怕来更好之控制权了,可以以着咱的想想贯彻其效果。但是如果当重新实现小辛苦,而且有时为没必要,拿我们就算足以连续DefaultControllerFactory类型,针对一定的办法去扩大,实现我们和好之功力要求。比如我们想多Ioc,有了IOC可以解耦Controller和Model的涉嫌。一般的话,Controller实例的缔造才用IOC容器的决定,我们直接由DefaultControllerFactory类型继承,重写Controller实例创建的逻辑即可,这样吧避免了整更实现,做打从来即使重新划算了。

桂林象鼻山

     上平等首稿子有了讲述,我们以此间大概说一下。ASP.NET
的路由系统是立以一个叫做UrlRoutingModule的HttpModule组件上的,针对请求的路由解析是由此挂号HttpApplication对象的PostResolveRequestCache事件来实现的,为目前底求动态映射到一个HttpHandler类型上,最终由该HttpHandler接管请求并拍卖。我们来看看UrlRoutingModule类型的代码吧。

桂林山水甲天下。

IControllerFactory controllerFactory = this._controllerFactory ?? ControllerBuilder.Current.GetControllerFactory();

使是,为什么会发这么多铜臭的气味,又为什么会时有发生如此多在的无奈。

     
如果我们还是尚未找到怎么处置为?我们即将看能免可知以后备命名空间,如果可以,就根据这命名空间来找,我们由RouteData路由数据的DataTokens属性中寻觅是否包含有Key为“UseNamespaceFallback”的价,如果发生,并且是False,就径直归,结束查找,如果无带有Key为“UseNamepsaceFallback”的价值或者该值为True,我们尽管好依据ControllerBuilder的DefaultNamespaces属性表示后备命名空间查找Controller的路,同理,没有找到就回null,找到一个便作结果值直接回到,如果多受一个那就假设毁弃来大了。

柳州螺蛳粉

   
第二单跟老三只构造函数都有一个IControllerActivator类型的参数,第三独凡是程序集里的,暂时无说,就说第二咔嚓,DefaultControllerFactory正式通过该参数来创造目标Controller对象的,我们根据ControllerActivator对象来创造一个DefaultControllerFactory对象,他会晤最终深受用来创造目标的Controller对象,我们的扩展点也便找到了。

————————————————————

        
系统遭到动用的DependencyResolver是经过DependencyResolver类型注册的。DependencyResolver类型有一个名叫Current的静态属性,该属性表示的凡当下底、IDependencyResolver类型的对象。我们可由此静态方法SetResolver来注册IDependencyResolver对象。需要证明一些,还有静态方法的DependencyResolver类型并没有落实IDependencyResolver接口,所以说该类型并无是当真的DependencyResolver类型,我们好将她知道也一个Facade,它集中了所设运用的对象和方法而已,使用还便民。

同桌等站变成三排,挤在特别为游客搭建之照相台阶上,扬起手来,大声喊茄子。

public interface IRouteHandler
{
    IHttpHandler GetHttpHandler(RequestContext requestContext);
}

广西丁的一致龙,是从米粉开始之。广西起螺蛳粉、老友粉、卤菜粉、生料粉、卷粉……作为半单广西人口,上述的刷我为主还吃罢。

  1    public class MvcHandler : IHttpAsyncHandler, IHttpHandler, IRequiresSessionState
  2     {
  3         private struct ProcessRequestState
  4         {
  5             internal IAsyncController AsyncController;
  6 
  7             internal IControllerFactory Factory;
  8 
  9             internal RequestContext RequestContext;
 10 
 11             internal void ReleaseController()
 12             {
 13                 this.Factory.ReleaseController(this.AsyncController);
 14             }
 15         }
 16 
 17         private static readonly object _processRequestTag = new object();
 18 
 19         internal static readonly string MvcVersion = MvcHandler.GetMvcVersionString();
 20 
 21         /// <summary>Contains the header name of the ASP.NET MVC version.</summary>
 22         public static readonly string MvcVersionHeaderName = "X-AspNetMvc-Version";
 23 
 24         private ControllerBuilder _controllerBuilder;
 25 
 26         internal ControllerBuilder ControllerBuilder
 27         {
 28             get
 29             {
 30                 if (this._controllerBuilder == null)
 31                 {
 32                     this._controllerBuilder = ControllerBuilder.Current;
 33                 }
 34                 return this._controllerBuilder;
 35             }
 36             set
 37             {
 38                 this._controllerBuilder = value;
 39             }
 40         }
 41 
 42         /// <summary>Gets or sets a value that indicates whether the MVC response header is disabled.</summary>
 43         /// <returns>true if the MVC response header is disabled; otherwise, false.</returns>
 44         public static bool DisableMvcResponseHeader
 45         {
 46             get;
 47             set;
 48         }
 49 
 50         /// <summary>Gets a value that indicates whether another request can use the <see cref="T:System.Web.IHttpHandler" /> instance.</summary>
 51         /// <returns>true if the <see cref="T:System.Web.IHttpHandler" /> instance is reusable; otherwise, false.</returns>
 52         protected virtual bool IsReusable
 53         {
 54             get
 55             {
 56                 return false;
 57             }
 58         }
 59 
 60         /// <summary>Gets the request context.</summary>
 61         /// <returns>The request context.</returns>
 62         public RequestContext RequestContext
 63         {
 64             get;
 65             private set;
 66         }
 67 
 68         /// <summary>Gets a value that indicates whether another request can use the <see cref="T:System.Web.IHttpHandler" /> instance.</summary>
 69         /// <returns>true if the <see cref="T:System.Web.IHttpHandler" /> instance is reusable; otherwise, false.</returns>
 70         bool IHttpHandler.IsReusable
 71         {
 72             get
 73             {
 74                 return this.IsReusable;
 75             }
 76         }
 77 
 78         /// <summary>Initializes a new instance of the <see cref="T:System.Web.Mvc.MvcHandler" /> class.</summary>
 79         /// <param name="requestContext">The request context.</param>
 80         /// <exception cref="T:System.ArgumentNullException">The <paramref name="requestContext" /> parameter is null.</exception>
 81         public MvcHandler(RequestContext requestContext)
 82         {
 83             if (requestContext == null)
 84             {
 85                 throw new ArgumentNullException("requestContext");
 86             }
 87             this.RequestContext = requestContext;
 88         }
 89 
 90         /// <summary>Adds the version header by using the specified HTTP context.</summary>
 91         /// <param name="httpContext">The HTTP context.</param>
 92         protected internal virtual void AddVersionHeader(HttpContextBase httpContext)
 93         {
 94             if (!MvcHandler.DisableMvcResponseHeader)
 95             {
 96                 httpContext.Response.AppendHeader(MvcHandler.MvcVersionHeaderName, MvcHandler.MvcVersion);
 97             }
 98         }
 99 
100         /// <summary>Called by ASP.NET to begin asynchronous request processing.</summary>
101         /// <returns>The status of the asynchronous call.</returns>
102         /// <param name="httpContext">The HTTP context.</param>
103         /// <param name="callback">The asynchronous callback method.</param>
104         /// <param name="state">The state of the asynchronous object.</param>
105         protected virtual IAsyncResult BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, object state)
106         {
107             HttpContextBase httpContext2 = new HttpContextWrapper(httpContext);
108             return this.BeginProcessRequest(httpContext2, callback, state);
109         }
110 
111         /// <summary>Called by ASP.NET to begin asynchronous request processing using the base HTTP context.</summary>
112         /// <returns>The status of the asynchronous call.</returns>
113         /// <param name="httpContext">The HTTP context.</param>
114         /// <param name="callback">The asynchronous callback method.</param>
115         /// <param name="state">The state of the asynchronous object.</param>
116         protected internal virtual IAsyncResult BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, object state)
117         {
118             IController controller;
119             IControllerFactory factory;
120             this.ProcessRequestInit(httpContext, out controller, out factory);
121             IAsyncController asyncController = controller as IAsyncController;
122             if (asyncController != null)
123             {
124                 BeginInvokeDelegate<MvcHandler.ProcessRequestState> beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState, MvcHandler.ProcessRequestState innerState)
125                 {
126                     IAsyncResult result;
127                     try
128                     {
129                         result = innerState.AsyncController.BeginExecute(innerState.RequestContext, asyncCallback, asyncState);
130                     }
131                     catch
132                     {
133                         innerState.ReleaseController();
134                         throw;
135                     }
136                     return result;
137                 };
138                 EndInvokeVoidDelegate<MvcHandler.ProcessRequestState> endDelegate = delegate(IAsyncResult asyncResult, MvcHandler.ProcessRequestState innerState)
139                 {
140                     try
141                     {
142                         innerState.AsyncController.EndExecute(asyncResult);
143                     }
144                     finally
145                     {
146                         innerState.ReleaseController();
147                     }
148                 };
149                 MvcHandler.ProcessRequestState invokeState = new MvcHandler.ProcessRequestState
150                 {
151                     AsyncController = asyncController,
152                     Factory = factory,
153                     RequestContext = this.RequestContext
154                 };
155                 SynchronizationContext synchronizationContext = SynchronizationContextUtil.GetSynchronizationContext();
156                 return AsyncResultWrapper.Begin<MvcHandler.ProcessRequestState>(callback, state, beginDelegate, endDelegate, invokeState, MvcHandler._processRequestTag, -1, synchronizationContext);
157             }
158             Action action = delegate
159             {
160                 try
161                 {
162                     controller.Execute(this.RequestContext);
163                 }
164                 finally
165                 {
166                     factory.ReleaseController(controller);
167                 }
168             };
169             return AsyncResultWrapper.BeginSynchronous(callback, state, action, MvcHandler._processRequestTag);
170         }
171 
172         /// <summary>Called by ASP.NET when asynchronous request processing has ended.</summary>
173         /// <param name="asyncResult">The asynchronous result.</param>
174         protected internal virtual void EndProcessRequest(IAsyncResult asyncResult)
175         {
176             AsyncResultWrapper.End(asyncResult, MvcHandler._processRequestTag);
177         }
178 
179         private static string GetMvcVersionString()
180         {
181             return new AssemblyName(typeof(MvcHandler).Assembly.FullName).Version.ToString(2);
182         }
183 
184         /// <summary>Processes the request by using the specified HTTP request context.</summary>
185         /// <param name="httpContext">The HTTP context.</param>
186         protected virtual void ProcessRequest(HttpContext httpContext)
187         {
188             HttpContextBase httpContext2 = new HttpContextWrapper(httpContext);
189             this.ProcessRequest(httpContext2);
190         }
191 
192         /// <summary>Processes the request by using the specified base HTTP request context.</summary>
193         /// <param name="httpContext">The HTTP context.</param>
194         protected internal virtual void ProcessRequest(HttpContextBase httpContext)
195         {
196             IController controller;
197             IControllerFactory controllerFactory;
198             this.ProcessRequestInit(httpContext, out controller, out controllerFactory);
199             try
200             {
201                 controller.Execute(this.RequestContext);
202             }
203             finally
204             {
205                 controllerFactory.ReleaseController(controller);
206             }
207         }
208 
209         private void ProcessRequestInit(HttpContextBase httpContext, out IController controller, out IControllerFactory factory)
210         {
211             HttpContext current = HttpContext.Current;
212             if (current != null && ValidationUtility.IsValidationEnabled(current) == true)
213             {
214                 ValidationUtility.EnableDynamicValidation(current);
215             }
216             this.AddVersionHeader(httpContext);
217             this.RemoveOptionalRoutingParameters();
218             string requiredString = this.RequestContext.RouteData.GetRequiredString("controller");
219             factory = this.ControllerBuilder.GetControllerFactory();
220             controller = factory.CreateController(this.RequestContext, requiredString);
221             if (controller == null)
222             {
223                 throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, MvcResources.ControllerBuilder_FactoryReturnedNull, new object[]
224                 {
225                     factory.GetType(),
226                     requiredString
227                 }));
228             }
229         }
230 
231         private void RemoveOptionalRoutingParameters()
232         {
233             RouteValueDictionary values = this.RequestContext.RouteData.Values;
234             values.RemoveFromDictionary((KeyValuePair<string, object> entry) => entry.Value == UrlParameter.Optional);
235         }
236 
237         /// <summary>Enables processing of HTTP Web requests by a custom HTTP handler that implements the <see cref="T:System.Web.IHttpHandler" /> interface.</summary>
238         /// <param name="httpContext">An <see cref="T:System.Web.HttpContext" /> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) that are used to service HTTP requests.</param>
239         void IHttpHandler.ProcessRequest(HttpContext httpContext)
240         {
241             this.ProcessRequest(httpContext);
242         }
243 
244         /// <summary>Called by ASP.NET to begin asynchronous request processing using the base HTTP context.</summary>
245         /// <returns>The status of the asynchronous call.</returns>
246         /// <param name="context">The HTTP context.</param>
247         /// <param name="cb">The asynchronous callback method.</param>
248         /// <param name="extraData">The data.</param>
249         IAsyncResult IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
250         {
251             return this.BeginProcessRequest(context, cb, extraData);
252         }
253 
254         /// <summary>Called by ASP.NET when asynchronous request processing has ended.</summary>
255         /// <param name="result">The asynchronous result.</param>
256         void IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)
257         {
258             this.EndProcessRequest(result);
259         }
260     }

咱失去矣西街。

    最后实现的代码如下:

西街底商业味很浓。但是及时吗无妨碍它的文艺气和烟火气。

    
我先行来简述一下Controller解析的原理吧。Controller实例对象的解析是由此实现了IControllerFactory接口的ControllerFactory对象实现的,ControllerFactory是怎来之为?是经过调用ControllerBuilder的SetControllerFactory方法实现对ControllerFactory类型或者实例对象的挂号。如果我们没有调用ControllerBuilder的SetControllerFactory方法对象ControllerFactory类型或者实例显示注册,系统会以默认的ControllerFactory来成功对Controller对象的剖析,这个目标就是DefaultControllerFactory类型,该型的实现正反映了ASP.NET
MVC框架对Controller实例的激活采取的默认策略。今天我们便看看DefaultControllerFactory类型是怎拿Controller对象激活的,这吗是Controller激活系统的默认实现,我们好扩展ControllerFactory类型,实现由定义之Controller激活策略。

桂林米粉

     
到了今天,Controller激活系统即写的大多了,唯一尚不一一点底虽是扩张点还没取。ASP.NET
MVC号称几乎任何地方都得以扩展,Controller激活系统受势必为含有在扩展点,下来我们各个详述。

喀斯特地貌,是具有溶蚀力的巡对可溶性岩石(大多为石灰岩)进行溶蚀作用等所形成的地表及暗形态的总称,又如岩溶地貌。

         
代码很粗略,我们将分析出的Controller类型作为参数调用UnityContainer对象的Resolve方法,进而赢得终极激活的Controller对象。这是样例代码,具体品种蒙,还要引入Unity的DLL,还需要注册,这些我就非细心说了。

故而那天下午,我们发时空错开游一游位于桂林城厢的象鼻山。

         
其实DefaultControllerActivator对象要像创建目标Controller对象,还凭借另外一个给DependencyResolver的对象。所有的DenpendencyResolver类型均贯彻了IDenpendencyResolver接口,接口定义如下:

本身读研的下实验室有只稍伙伴是广西柳州总人口,喜欢带螺蛳粉来划分被多少伙伴。中华物产店的螺蛳粉800日元一兜子,合约50人民币,想吃的时刻咬咬牙还是得进。

    
我将代码流程写一下,在MvcHandler类型里面有一定量独艺术,一个主意是:BeginProcessRequest(HttpContextBase
httpContext,AsyncCallback callback,object
state),该方法用于对要进行拍卖;第二只法子是:ProcessRequestInit(HttpContextbase
httpContext,out IController controller,out IControllerFactory
controllerFactory),该法就是是概念了激活Controller算法的骨子,上代码吧,代码最无第二全,我们事先看BeginProcessRequest的代码:

 ==================================

 1 /// <summary>Creates an object that implements the IHttpHandler interface and passes the request context to it.</summary>
 2 public class MvcRouteHandler : IRouteHandler
 3 {
 4     private IControllerFactory _controllerFactory;
 5 
 6     /// <summary>Initializes a new instance of the <see cref="T:System.Web.Mvc.MvcRouteHandler" /> class.</summary>
 7     public MvcRouteHandler()
 8     {
 9     }
10 
11     /// <summary>Initializes a new instance of the <see cref="T:System.Web.Mvc.MvcRouteHandler" /> class using the specified factory controller object.</summary>
12     /// <param name="controllerFactory">The controller factory.</param>
13     public MvcRouteHandler(IControllerFactory controllerFactory)
14     {
15         this._controllerFactory = controllerFactory;
16     }
17 
18     /// <summary>Returns the HTTP handler by using the specified HTTP context.</summary>
19     /// <returns>The HTTP handler.</returns>
20     /// <param name="requestContext">The request context.</param>
21     protected virtual IHttpHandler GetHttpHandler(RequestContext requestContext)
22     {
23             requestContext.HttpContext.SetSessionStateBehavior(this.GetSessionStateBehavior(requestContext));
24         return new MvcHandler(requestContext);
25     }
26 
27     /// <summary>Returns the session behavior.</summary>
28     /// <returns>The session behavior.</returns>
29     /// <param name="requestContext">The request context.</param>
30     protected virtual SessionStateBehavior GetSessionStateBehavior(RequestContext requestContext)
31     {
32         string text = (string)requestContext.RouteData.Values["controller"];
33         if (string.IsNullOrWhiteSpace(text))
34         {
35             throw new InvalidOperationException(MvcResources.MvcRouteHandler_RouteValuesHasNoController);
36         }
37         IControllerFactory controllerFactory = this._controllerFactory ?? ControllerBuilder.Current.GetControllerFactory();
38         return controllerFactory.GetControllerSessionBehavior(requestContext, text);
39     }
40 
41     /// <summary>Returns the HTTP handler by using the specified request context.</summary>
42     /// <returns>The HTTP handler.</returns>
43     /// <param name="requestContext">The request context.</param>
44     IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext)
45     {
46         return this.GetHttpHandler(requestContext);
47     }
48 }

 
MvcRouteHandler实现了IRouteHandler接口,目的无非来一个,提供后续之HttpHandler,IRouteHandler接口定义如下:

除去桂林之米面,我还眷恋取一词柳州螺蛳粉。

          
这个方式是用以创造Controller实例的,这里刚可以动用IOC容器来保管Controller实例,当然在DefaultControllerFactory类型中尚闹另外的扩展点,大家可友善失去押,全部代码我以前也贴出过。

图 // 来源于花瓣、百度

          
如果我们于构建DefaultControllerFactory对象的时刻从不展示指定采用的ControllerActiviator参数,则它会动用默认的一个ControllerActivator对象DefaultControllerActivator来形成,该型是一个私家类型,外界无法访问。源码如下:

顾念只要吃到江苏口味?那要想念的略多。

     protected internal virtual Type GetControllerType(RequestContext requestContext, string controllerName)

本人未专业的分解就是是,溶洞、天坑、奇崛山峰。

  
于斯办法中冲分析出的Controller的花色来实行,如果是异步的Controller那尽管异步执行,否则就是一块儿实施。在拖欠法中,第三尽,标红色的点子就是是概念解析及履Controller的算法骨架,就是咱们要贴代码的次只法子ProcessRequestInit,源码如下:
 

要无是,那以称作真的文艺?

     protected internal virtual IController GetControllerInstance(RequestContext requestContext, Type controllerType)

自我觉得文学,其实历来用人气,也用钞票。

   
我们好总结了,到之,Controler激活系统这小节己虽形容了了。其实不是十分复杂,大家以羁押之上,刚起转变太关爱代码的细节,先把总体数据流向,或者为请求脉络,把其中所干到之靶子同涉嫌都收拾清楚了,然后再发针对性的夺押关系到之每个对象,不是画图,不是画,是写各个对象期间的涉图,图会写出来,说明您的心尖便时有发生矣总体把握了。如果尽关心细节,太关注之一项目的代码,也会见怪爱顾此失彼,因为自开便是那么,总是看了背后忘记前面,请求的路也非是怪明亮。所以我们学习的当儿也只要出点子,方法对,学的即快,成就感就能够杀快有。好了,说了如此多了,继续着力吧,希望我勾勒的东西对大家享有帮助。

凡日雨纷纷,天色昏沉,远山要黛,弯月如钩,黄衣点点,笑颜如星。

   
我们先行根据RouteData路由数据来博取Controller的类别对象,如果RouteData不呢空,并且于RouteData的Values属性中隐含Key为“MS_DirectRouteMatches”的价,那我们尽管因故获取Controller的花色对象,如果没找到就回来Null值,如果有一个价,就会见当Controller的Type类型值返回,如果多为一个就算见面扔来好。如果RouteData不含Key为“MS_DirectRouteMatches”的价值,我们尽管冲RouteData对象被DataTokens属性Key为“Namespaces”来取得Controller的Type对象,同理,如果没找到就归null,找到一个便一直回,如果多余一个之语句虽丢来十分。

01.象鼻山

  
既然是ControllerFactory,DefaultControllerFactory肯定啊落实了IControllerFactory接口,别的我们就是无看了,我们看是怎创建Controller对象的,方法代码如下:

青春而您。

     我们扩大的源码如下:

螺蛳粉口味很蹊跷,醇厚浓郁。螺蛳粉胜在汤料,它的汤料由螺蛳肉、山奈、八角、肉桂、丁香、多种柿子椒、等天香精以及味精配制而成为。真正的螺蛳粉是尚未螺丝的,虽然本人实在深愿意会来硌螺丝尝一尝。

    好了,扩展点写完
,大家发出工夫足以望源码,可以生过多启发,获得的为又多。

 1 /// <summary>Retrieves the controller type for the specified name and request context.</summary>
 2 /// <returns>The controller type.</returns>
 3 /// <param name="requestContext">The context of the HTTP request, which includes the HTTP context and route data.</param>
 4 /// <param name="controllerName">The name of the controller.</param>
 5 protected internal virtual Type GetControllerType(RequestContext requestContext, string controllerName)
 6 {
 7     if (requestContext == null)
 8     {
 9         throw new ArgumentNullException("requestContext");
10     }
11     if (string.IsNullOrEmpty(controllerName) && (requestContext.RouteData == null || !requestContext.RouteData.HasDirectRouteMatch()))
12     {
13         throw new ArgumentException(MvcResources.Common_NullOrEmpty, "controllerName");
14     }
15     RouteData routeData = requestContext.RouteData;
16     if (routeData != null && routeData.HasDirectRouteMatch())
17     {
18         return DefaultControllerFactory.GetControllerTypeFromDirectRoute(routeData);
19     }
20     object obj;
21     if (routeData.DataTokens.TryGetValue("Namespaces", out obj))
22     {
23         IEnumerable<string> enumerable = obj as IEnumerable<string>;
24         if (enumerable != null && enumerable.Any<string>())
25         {
26             HashSet<string> namespaces = new HashSet<string>(enumerable, StringComparer.OrdinalIgnoreCase);
27             Type controllerTypeWithinNamespaces = this.GetControllerTypeWithinNamespaces(routeData.Route, controllerName, namespaces);
28             if (controllerTypeWithinNamespaces != null || false.Equals(routeData.DataTokens["UseNamespaceFallback"]))
29             {
30                 return controllerTypeWithinNamespaces;
31             }
32         }
33     }
34     if (this.ControllerBuilder.DefaultNamespaces.Count > 0)
35     {
36         HashSet<string> namespaces2 = new HashSet<string>(this.ControllerBuilder.DefaultNamespaces, StringComparer.OrdinalIgnoreCase);
37         Type controllerTypeWithinNamespaces = this.GetControllerTypeWithinNamespaces(routeData.Route, controllerName, namespaces2);
38         if (controllerTypeWithinNamespaces != null)
39         {
40             return controllerTypeWithinNamespaces;
41         }
42     }
43     return this.GetControllerTypeWithinNamespaces(routeData.Route, controllerName, null);
44 }

今我们聊桂林,当然要聊桂林米粉。桂林米粉大概和桂林山水一样甲天下了咔嚓。

 1 private class DefaultControllerActivator : IControllerActivator
 2 {
 3     private Func<IDependencyResolver> _resolverThunk;
 4 
 5     public DefaultControllerActivator() : this(null)
 6     {
 7     }
 8 
 9     public DefaultControllerActivator(IDependencyResolver resolver)
10     {
11         if (resolver == null)
12         {
13             this._resolverThunk = (() => DependencyResolver.Current);
14             return;
15         }
16         this._resolverThunk = (() => resolver);
17     }
18 
19     public IController Create(RequestContext requestContext, Type controllerType)
20     {
21         IController result;
22         try
23         {
24             result = (IController)(this._resolverThunk().GetService(controllerType) ?? Activator.CreateInstance(controllerType));
25         }
26         catch (Exception innerException)
27         {
28             throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, MvcResources.DefaultControllerFactory_ErrorCreatingController, new object[]
29             {
30                 controllerType
31             }), innerException);
32         }
33         return result;
34     }
35 }

自大四班级毕业游在桂林阳朔,我觉得能及不少好伴侣一起以那里告别青春,很完善。

 1         /// <summary>Called by ASP.NET to begin asynchronous request processing using the base HTTP context.</summary>
 2         /// <returns>The status of the asynchronous call.</returns>
 3         /// <param name="httpContext">The HTTP context.</param>
 4         /// <param name="callback">The asynchronous callback method.</param>
 5         /// <param name="state">The state of the asynchronous object.</param>
 6         protected internal virtual IAsyncResult BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, object state)
 7         {
 8             IController controller;
 9             IControllerFactory factory;
10             this.ProcessRequestInit(httpContext, out controller, out factory);
11             IAsyncController asyncController = controller as IAsyncController;
12             if (asyncController != null)
13             {
14                 BeginInvokeDelegate<MvcHandler.ProcessRequestState> beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState, MvcHandler.ProcessRequestState innerState)
15                 {
16                     IAsyncResult result;
17                     try
18                     {
19                         result = innerState.AsyncController.BeginExecute(innerState.RequestContext, asyncCallback, asyncState);
20                     }
21                     catch
22                     {
23                         innerState.ReleaseController();
24                         throw;
25                     }
26                     return result;
27                 };
28                 EndInvokeVoidDelegate<MvcHandler.ProcessRequestState> endDelegate = delegate(IAsyncResult asyncResult, MvcHandler.ProcessRequestState innerState)
29                 {
30                     try
31                     {
32                         innerState.AsyncController.EndExecute(asyncResult);
33                     }
34                     finally
35                     {
36                         innerState.ReleaseController();
37                     }
38                 };
39                 MvcHandler.ProcessRequestState invokeState = new MvcHandler.ProcessRequestState
40                 {
41                     AsyncController = asyncController,
42                     Factory = factory,
43                     RequestContext = this.RequestContext
44                 };
45                 SynchronizationContext synchronizationContext = SynchronizationContextUtil.GetSynchronizationContext();
46                 return AsyncResultWrapper.Begin<MvcHandler.ProcessRequestState>(callback, state, beginDelegate, endDelegate, invokeState, MvcHandler._processRequestTag, -1, synchronizationContext);
47             }
48             Action action = delegate
49             {
50                 try
51                 {
52                     controller.Execute(this.RequestContext);
53                 }
54                 finally
55                 {
56                     factory.ReleaseController(controller);
57                 }
58             };
59             return AsyncResultWrapper.BeginSynchronous(callback, state, action, MvcHandler._processRequestTag);
60         }

自我第一破当桂林城厢游玩是12年份,虽然那次啊单独是转发而已,但咱买的是次龙的汽车票。

 
MvcHandler类型的BeginProcessRequest方法用来处理要,包括激活Controller实例等。由于MvcHandler类型同时落实了IHttpHandler接口和IHttpAsyncHandler接口,所以他连异步方式去履行(调用BeginProcessRequest/EndProcessRequest方法)。BeginProcessRequest方法以推行之时光经过RequestContext对象的RouteData属性获得Controller的名字,然后于经过ControllerBuilder获得ControllerFactory对象,然后用Controller的讳和ControllerFactory对象来激活目标Controller实例。如果Controller类型实现了IAsyncController接口,那即便因为异步方式执行Controller,否则以同方式实施。Controller对象成实行后,MvcHandler对象见面调用ControllerFactory对象ReleaseController方法来销毁Controller实例对象。

单个读君告诉自己,现在风行的桂林米粉并无是桂林人数开的,是广西御等人做的,但是以便利宣传,借用了广西底深IP,桂林。勤劳的上等人带在即无异碗刷,走向了举国上下。

    
如果我们从来不针对DependencyResolver进行展示的报,则网会动一个默认的称之为DefaultDependencyResolver的目标,本对象呢是一个私家类型,外界无法利用。

12年前,我同爸妈一块儿错过之,门票不是我付的,我为非知道多少钱。

 1         private void ProcessRequestInit(HttpContextBase httpContext, out IController controller, out IControllerFactory factory)
 2         {
 3             HttpContext current = HttpContext.Current;
 4             if (current != null && ValidationUtility.IsValidationEnabled(current) == true)
 5             {
 6                 ValidationUtility.EnableDynamicValidation(current);
 7             }
 8             this.AddVersionHeader(httpContext);
 9             this.RemoveOptionalRoutingParameters();
10             string requiredString = this.RequestContext.RouteData.GetRequiredString("controller");
11             factory = this.ControllerBuilder.GetControllerFactory();
12             controller = factory.CreateController(this.RequestContext, requiredString);
13             if (controller == null)
14             {
15                 throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, MvcResources.ControllerBuilder_FactoryReturnedNull, new object[]
16                 {
17                     factory.GetType(),
18                     requiredString
19                 }));
20             }
21         }

 ==================================

  
该接口中定义了Create方法实现对对象Controller对象的创,两独参数分别表示请上下文和Controller的路。我们以看DefaultControllerFactory和ControllerActivator之间的干吧,DefaultControllerFactory类型有三只构造函数,代码如下:

自由桂林特别频繁,因为自己需要为飞机下滑桂林,然后直奔汽车站,再变动巴士。我对桂林绝熟悉的片个地方便是飞机场以及汽车站。

   
我们于达标同样篇稿子被介绍Controller激活系统受到所涉嫌到之一对列,比如有关Controller类型的有关定义类型就连了IController类型,IAsyncController类型,ControllerBase抽象类型和咱们最终使下的抽象类型Controller,这是ASP.NET
MVC
框架中以及Controller本身定义相关的门类。其他帮助项目,包括管制Controller的项目ControllerFactory,这个厂负责Controller的生及销毁。我们尚波及到外一个救助项目,用于把系统默认定义的抑打定义之ControllerFactory注册及ASP.NET
MVC框架中的类ControllerBuilder。

————————————————————

/// <summary>Provides fine-grained control over how controllers are instantiated using dependency injection.</summary>
public interface IControllerActivator
{
    /// <summary>When implemented in a class, creates a controller.</summary>
    /// <returns>The created controller.</returns>
    /// <param name="requestContext">The request context.</param>
    /// <param name="controllerType">The controller type.</param>
    IController Create(RequestContext requestContext, Type controllerType);
}

自是江苏人,但是自己经常去广西,因为我妈是只广西口。

    
当我们通过无参的构造函数或者经过将ControllerActivator参数指定为null的构造函数来创造DefaultControllerFactory实例的当儿,那么用于激活Controller实例的将是经过DependencyResolver类型的静态属性Current表示的DependencyResolver对象来激活的,我们的扩大终于啊找到了。

商业街的文艺,是无是文学?

 1 /// <summary>Initializes a new instance of the <see cref="T:System.Web.Mvc.DefaultControllerFactory" /> class.</summary>
 2 public DefaultControllerFactory() : this(null, null, null)
 3 {
 4 }
 5 
 6 /// <summary>Initializes a new instance of the <see cref="T:System.Web.Mvc.DefaultControllerFactory" /> class using a controller activator.</summary>
 7 /// <param name="controllerActivator">An object that implements the controller activator interface.</param>
 8 public DefaultControllerFactory(IControllerActivator controllerActivator) : this(controllerActivator, null, null)
 9 {
10 }
11 
12 internal DefaultControllerFactory(IControllerActivator controllerActivator, IResolver<IControllerActivator> activatorResolver, IDependencyResolver dependencyResolver)
13 {
14     if (controllerActivator != null)
15     {
16         this._controllerActivator = controllerActivator;
17         return;
18     }
19     IResolver<IControllerActivator> arg_44_1 = activatorResolver;
20     if (activatorResolver == null)
21     {
22         arg_44_1 = new SingleServiceResolver<IControllerActivator>(() => null, new DefaultControllerFactory.DefaultControllerActivator(dependencyResolver), "DefaultControllerFactory constructor");
23     }
24     this._activatorResolver = arg_44_1;
25 }

愉悦而你。

      扩张点同样:扩展IControllerFactory接口

02.阳朔

四、小结

文 // 安田里

 1 /// <summary>Creates the specified controller by using the specified request context.</summary>
 2 /// <returns>The controller.</returns>
 3 /// <param name="requestContext">The context of the HTTP request, which includes the HTTP context and route data.</param>
 4 /// <param name="controllerName">The name of the controller.</param>
 5 /// <exception cref="T:System.ArgumentNullException">The <paramref name="requestContext" /> parameter is null.</exception>
 6 /// <exception cref="T:System.ArgumentException">The <paramref name="controllerName" /> parameter is null or empty.</exception>
 7 public virtual IController CreateController(RequestContext requestContext, string controllerName)
 8 {
 9     if (requestContext == null)
10     {
11         throw new ArgumentNullException("requestContext");
12     }
13     if (string.IsNullOrEmpty(controllerName) && !requestContext.RouteData.HasDirectRouteMatch())
14     {
15         throw new ArgumentException(MvcResources.Common_NullOrEmpty, "controllerName");
16     }
17     Type controllerType = this.GetControllerType(requestContext, controllerName);
18     return this.GetControllerInstance(requestContext, controllerType);
19 }

 

   
我们今天关键谈Controller是怎解析出的,之所以将及时等同有分离写,因为合在一起太长了,也说的未详细,如果大家对上述说之免太了解,可以查《白话ASP.NET
MVC之二:Controller激活系统的概览》,  该文对ASP.NET
MVC框架中所波及的Controlelr激活系统所波及的种有详尽的介绍。

怀有着这些的阳朔,是天堂赐予桂林的传家宝。

   
好了,大概的逻辑写了了,如果还发出无亮堂的,就仔细的探访源码拿,如果拿源码完整的禁闭无异全副,然后以整治逻辑,就容易多矣。看代码别太在意代码细节,关注主要的关键点或者让关键类就得,把哥哥类之间的涉及和责任整理清楚,理解起来并无复杂。

————————————————————————————

          
DefaultControllerFactory对象并无直激活目标Controller对象,真正激活Controller对象的凡一个称作ControllerActiviator类型的目标,换句话说,DefaultControllerFactory对象委托ControllerActivator对象根据分析出类型创建对承诺Controller对象。所有的ControllerActivator对象全实现IControllerActivator接口,该接口定义如下:

本身大学之隔壁发生同样贱卖螺蛳粉的小店,广西气味,让自家想起了温馨之一半独乡。

     扩展点二:扩展ControllerActivator

十里画廊可圈之山水最多,我们挑了月亮山。因为突下暴雨,我们当错过之旅途纷纷购买了艳的一次性雨披。

  1 /// <summary>Represents the controller factory that is registered by default.</summary>
  2     public class DefaultControllerFactory : IControllerFactory
  3     {
  4         private class DefaultControllerActivator : IControllerActivator
  5         {
  6             private Func<IDependencyResolver> _resolverThunk;
  7 
  8             public DefaultControllerActivator() : this(null)
  9             {
 10             }
 11 
 12             public DefaultControllerActivator(IDependencyResolver resolver)
 13             {
 14                 if (resolver == null)
 15                 {
 16                     this._resolverThunk = (() => DependencyResolver.Current);
 17                     return;
 18                 }
 19                 this._resolverThunk = (() => resolver);
 20             }
 21 
 22             public IController Create(RequestContext requestContext, Type controllerType)
 23             {
 24                 IController result;
 25                 try
 26                 {
 27                     result = (IController)(this._resolverThunk().GetService(controllerType) ?? Activator.CreateInstance(controllerType));
 28                 }
 29                 catch (Exception innerException)
 30                 {
 31                     throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, MvcResources.DefaultControllerFactory_ErrorCreatingController, new object[]
 32                     {
 33                         controllerType
 34                     }), innerException);
 35                 }
 36                 return result;
 37             }
 38         }
 39 
 40         private static readonly ConcurrentDictionary<Type, SessionStateBehavior> _sessionStateCache = new ConcurrentDictionary<Type, SessionStateBehavior>();
 41 
 42         private static ControllerTypeCache _staticControllerTypeCache = new ControllerTypeCache();
 43 
 44         private IBuildManager _buildManager;
 45 
 46         private IResolver<IControllerActivator> _activatorResolver;
 47 
 48         private IControllerActivator _controllerActivator;
 49 
 50         private ControllerBuilder _controllerBuilder;
 51 
 52         private ControllerTypeCache _instanceControllerTypeCache;
 53 
 54         private IControllerActivator ControllerActivator
 55         {
 56             get
 57             {
 58                 if (this._controllerActivator != null)
 59                 {
 60                     return this._controllerActivator;
 61                 }
 62                 this._controllerActivator = this._activatorResolver.Current;
 63                 return this._controllerActivator;
 64             }
 65         }
 66 
 67         internal IBuildManager BuildManager
 68         {
 69             get
 70             {
 71                 if (this._buildManager == null)
 72                 {
 73                     this._buildManager = new BuildManagerWrapper();
 74                 }
 75                 return this._buildManager;
 76             }
 77             set
 78             {
 79                 this._buildManager = value;
 80             }
 81         }
 82 
 83         internal ControllerBuilder ControllerBuilder
 84         {
 85             get
 86             {
 87                 return this._controllerBuilder ?? ControllerBuilder.Current;
 88             }
 89             set
 90             {
 91                 this._controllerBuilder = value;
 92             }
 93         }
 94 
 95         internal ControllerTypeCache ControllerTypeCache
 96         {
 97             get
 98             {
 99                 return this._instanceControllerTypeCache ?? DefaultControllerFactory._staticControllerTypeCache;
100             }
101             set
102             {
103                 this._instanceControllerTypeCache = value;
104             }
105         }
106 
107         /// <summary>Initializes a new instance of the <see cref="T:System.Web.Mvc.DefaultControllerFactory" /> class.</summary>
108         public DefaultControllerFactory() : this(null, null, null)
109         {
110         }
111 
112         /// <summary>Initializes a new instance of the <see cref="T:System.Web.Mvc.DefaultControllerFactory" /> class using a controller activator.</summary>
113         /// <param name="controllerActivator">An object that implements the controller activator interface.</param>
114         public DefaultControllerFactory(IControllerActivator controllerActivator) : this(controllerActivator, null, null)
115         {
116         }
117 
118         internal DefaultControllerFactory(IControllerActivator controllerActivator, IResolver<IControllerActivator> activatorResolver, IDependencyResolver dependencyResolver)
119         {
120             if (controllerActivator != null)
121             {
122                 this._controllerActivator = controllerActivator;
123                 return;
124             }
125             IResolver<IControllerActivator> arg_44_1 = activatorResolver;
126             if (activatorResolver == null)
127             {
128                 arg_44_1 = new SingleServiceResolver<IControllerActivator>(() => null, new DefaultControllerFactory.DefaultControllerActivator(dependencyResolver), "DefaultControllerFactory constructor");
129             }
130             this._activatorResolver = arg_44_1;
131         }
132 
133         internal static InvalidOperationException CreateAmbiguousControllerException(RouteBase route, string controllerName, ICollection<Type> matchingTypes)
134         {
135             StringBuilder stringBuilder = new StringBuilder();
136             foreach (Type current in matchingTypes)
137             {
138                 stringBuilder.AppendLine();
139                 stringBuilder.Append(current.FullName);
140             }
141             Route route2 = route as Route;
142             string message;
143             if (route2 != null)
144             {
145                 message = string.Format(CultureInfo.CurrentCulture, MvcResources.DefaultControllerFactory_ControllerNameAmbiguous_WithRouteUrl, new object[]
146                 {
147                     controllerName,
148                     route2.Url,
149                     stringBuilder,
150                     Environment.NewLine
151                 });
152             }
153             else
154             {
155                 message = string.Format(CultureInfo.CurrentCulture, MvcResources.DefaultControllerFactory_ControllerNameAmbiguous_WithoutRouteUrl, new object[]
156                 {
157                     controllerName,
158                     stringBuilder,
159                     Environment.NewLine
160                 });
161             }
162             return new InvalidOperationException(message);
163         }
164 
165         private static InvalidOperationException CreateDirectRouteAmbiguousControllerException(ICollection<Type> matchingTypes)
166         {
167             StringBuilder stringBuilder = new StringBuilder();
168             foreach (Type current in matchingTypes)
169             {
170                 stringBuilder.AppendLine();
171                 stringBuilder.Append(current.FullName);
172             }
173             string message = string.Format(CultureInfo.CurrentCulture, MvcResources.DefaultControllerFactory_DirectRouteAmbiguous, new object[]
174             {
175                 stringBuilder,
176                 Environment.NewLine
177             });
178             return new InvalidOperationException(message);
179         }
180 
181         /// <summary>Creates the specified controller by using the specified request context.</summary>
182         /// <returns>The controller.</returns>
183         /// <param name="requestContext">The context of the HTTP request, which includes the HTTP context and route data.</param>
184         /// <param name="controllerName">The name of the controller.</param>
185         /// <exception cref="T:System.ArgumentNullException">The <paramref name="requestContext" /> parameter is null.</exception>
186         /// <exception cref="T:System.ArgumentException">The <paramref name="controllerName" /> parameter is null or empty.</exception>
187         public virtual IController CreateController(RequestContext requestContext, string controllerName)
188         {
189             if (requestContext == null)
190             {
191                 throw new ArgumentNullException("requestContext");
192             }
193             if (string.IsNullOrEmpty(controllerName) && !requestContext.RouteData.HasDirectRouteMatch())
194             {
195                 throw new ArgumentException(MvcResources.Common_NullOrEmpty, "controllerName");
196             }
197             Type controllerType = this.GetControllerType(requestContext, controllerName);
198             return this.GetControllerInstance(requestContext, controllerType);
199         }
200 
201         /// <summary>Retrieves the controller instance for the specified request context and controller type.</summary>
202         /// <returns>The controller instance.</returns>
203         /// <param name="requestContext">The context of the HTTP request, which includes the HTTP context and route data.</param>
204         /// <param name="controllerType">The type of the controller.</param>
205         /// <exception cref="T:System.Web.HttpException">
206         ///   <paramref name="controllerType" /> is null.</exception>
207         /// <exception cref="T:System.ArgumentException">
208         ///   <paramref name="controllerType" /> cannot be assigned.</exception>
209         /// <exception cref="T:System.InvalidOperationException">An instance of <paramref name="controllerType" /> cannot be created.</exception>
210         protected internal virtual IController GetControllerInstance(RequestContext requestContext, Type controllerType)
211         {
212             if (controllerType == null)
213             {
214                 throw new HttpException(404, string.Format(CultureInfo.CurrentCulture, MvcResources.DefaultControllerFactory_NoControllerFound, new object[]
215                 {
216                     requestContext.HttpContext.Request.Path
217                 }));
218             }
219             if (!typeof(IController).IsAssignableFrom(controllerType))
220             {
221                 throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, MvcResources.DefaultControllerFactory_TypeDoesNotSubclassControllerBase, new object[]
222                 {
223                     controllerType
224                 }), "controllerType");
225             }
226             return this.ControllerActivator.Create(requestContext, controllerType);
227         }
228 
229         /// <summary>Returns the controller's session behavior.</summary>
230         /// <returns>The controller's session behavior.</returns>
231         /// <param name="requestContext">The request context.</param>
232         /// <param name="controllerType">The type of the controller.</param>
233         protected internal virtual SessionStateBehavior GetControllerSessionBehavior(RequestContext requestContext, Type controllerType)
234         {
235             if (controllerType == null)
236             {
237                 return SessionStateBehavior.Default;
238             }
239             return DefaultControllerFactory._sessionStateCache.GetOrAdd(controllerType, delegate(Type type)
240             {
241                 SessionStateAttribute sessionStateAttribute = type.GetCustomAttributes(typeof(SessionStateAttribute), true).OfType<SessionStateAttribute>().FirstOrDefault<SessionStateAttribute>();
242                 if (sessionStateAttribute == null)
243                 {
244                     return SessionStateBehavior.Default;
245                 }
246                 return sessionStateAttribute.Behavior;
247             });
248         }
249 
250         /// <summary>Retrieves the controller type for the specified name and request context.</summary>
251         /// <returns>The controller type.</returns>
252         /// <param name="requestContext">The context of the HTTP request, which includes the HTTP context and route data.</param>
253         /// <param name="controllerName">The name of the controller.</param>
254         protected internal virtual Type GetControllerType(RequestContext requestContext, string controllerName)
255         {
256             if (requestContext == null)
257             {
258                 throw new ArgumentNullException("requestContext");
259             }
260             if (string.IsNullOrEmpty(controllerName) && (requestContext.RouteData == null || !requestContext.RouteData.HasDirectRouteMatch()))
261             {
262                 throw new ArgumentException(MvcResources.Common_NullOrEmpty, "controllerName");
263             }
264             RouteData routeData = requestContext.RouteData;
265             if (routeData != null && routeData.HasDirectRouteMatch())
266             {
267                 return DefaultControllerFactory.GetControllerTypeFromDirectRoute(routeData);
268             }
269             object obj;
270             if (routeData.DataTokens.TryGetValue("Namespaces", out obj))
271             {
272                 IEnumerable<string> enumerable = obj as IEnumerable<string>;
273                 if (enumerable != null && enumerable.Any<string>())
274                 {
275                     HashSet<string> namespaces = new HashSet<string>(enumerable, StringComparer.OrdinalIgnoreCase);
276                     Type controllerTypeWithinNamespaces = this.GetControllerTypeWithinNamespaces(routeData.Route, controllerName, namespaces);
277                     if (controllerTypeWithinNamespaces != null || false.Equals(routeData.DataTokens["UseNamespaceFallback"]))
278                     {
279                         return controllerTypeWithinNamespaces;
280                     }
281                 }
282             }
283             if (this.ControllerBuilder.DefaultNamespaces.Count > 0)
284             {
285                 HashSet<string> namespaces2 = new HashSet<string>(this.ControllerBuilder.DefaultNamespaces, StringComparer.OrdinalIgnoreCase);
286                 Type controllerTypeWithinNamespaces = this.GetControllerTypeWithinNamespaces(routeData.Route, controllerName, namespaces2);
287                 if (controllerTypeWithinNamespaces != null)
288                 {
289                     return controllerTypeWithinNamespaces;
290                 }
291             }
292             return this.GetControllerTypeWithinNamespaces(routeData.Route, controllerName, null);
293         }
294 
295         private static Type GetControllerTypeFromDirectRoute(RouteData routeData)
296         {
297             IEnumerable<RouteData> directRouteMatches = routeData.GetDirectRouteMatches();
298             List<Type> list = new List<Type>();
299             foreach (RouteData current in directRouteMatches)
300             {
301                 if (current != null)
302                 {
303                     Type targetControllerType = current.GetTargetControllerType();
304                     if (targetControllerType == null)
305                     {
306                         throw new InvalidOperationException(MvcResources.DirectRoute_MissingControllerType);
307                     }
308                     if (!list.Contains(targetControllerType))
309                     {
310                         list.Add(targetControllerType);
311                     }
312                 }
313             }
314             if (list.Count == 0)
315             {
316                 return null;
317             }
318             if (list.Count == 1)
319             {
320                 return list[0];
321             }
322             throw DefaultControllerFactory.CreateDirectRouteAmbiguousControllerException(list);
323         }
324 
325         private Type GetControllerTypeWithinNamespaces(RouteBase route, string controllerName, HashSet<string> namespaces)
326         {
327             this.ControllerTypeCache.EnsureInitialized(this.BuildManager);
328             ICollection<Type> controllerTypes = this.ControllerTypeCache.GetControllerTypes(controllerName, namespaces);
329             switch (controllerTypes.Count)
330             {
331             case 0:
332                 return null;
333             case 1:
334                 return controllerTypes.First<Type>();
335             default:
336                 throw DefaultControllerFactory.CreateAmbiguousControllerException(route, controllerName, controllerTypes);
337             }
338         }
339 
340         /// <summary>Releases the specified controller.</summary>
341         /// <param name="controller">The controller to release.</param>
342         public virtual void ReleaseController(IController controller)
343         {
344             IDisposable disposable = controller as IDisposable;
345             if (disposable != null)
346             {
347                 disposable.Dispose();
348             }
349         }
350 
351         internal IReadOnlyList<Type> GetControllerTypes()
352         {
353             this.ControllerTypeCache.EnsureInitialized(this.BuildManager);
354             return this.ControllerTypeCache.GetControllerTypes();
355         }
356 
357         /// <summary>This API supports the ASP.NET MVC infrastructure and is not intended to be used directly from your code. This method calls the <see cref="M:System.Web.Mvc.DefaultControllerFactory.GetControllerSessionBehavior(System.Web.Routing.RequestContext,System.Type)" /> method.</summary>
358         /// <returns>The controller's session behavior.</returns>
359         /// <param name="requestContext">The request context.</param>
360         /// <param name="controllerName">The controller name.</param>
361         SessionStateBehavior IControllerFactory.GetControllerSessionBehavior(RequestContext requestContext, string controllerName)
362         {
363             if (requestContext == null)
364             {
365                 throw new ArgumentNullException("requestContext");
366             }
367             if (string.IsNullOrEmpty(controllerName))
368             {
369                 throw new ArgumentException(MvcResources.Common_NullOrEmpty, "controllerName");
370             }
371             Type controllerType = this.GetControllerType(requestContext, controllerName);
372             return this.GetControllerSessionBehavior(requestContext, controllerType);
373         }
374     }

 

    
扩展写好了,还亟需以Global.asax文件之中进行挂号,否则不能够使。IOC相关的情节即非介绍了,大家好自行钻研。

但是象鼻山这景,也实在别具一格,对吧?

     我们总结一下,ASP.NET
MVC的路由系统以及Controller的激活系统是通过这些目标关联起来的:请求Url
——->Route——->RouteData——->RouteHandler(MvcRouteHandler)——–>MvcRouteHandler——>MvcHandler,通过这些目标就是可知差起来了。

————————————————————

 
代码很简单,该法赢得Controller的Type类型对象,然后根据Type对象创建实例。这个法中来零星只援方法,一个凡是GetControllerType方法,另一个凡GetControllerInstance方法,根据名称我们尽管能够掌握凡是举行呀的。我们先看GetControllerType方法的源码吧,这里是非同小可,没有Type对象的拿走,以后都是空言:  

枯水季节,天色暗,游客稀少,整个象鼻山都笼罩在同等片刺激雨朦胧中。我于石块边上蹿下跳,在各种奇异形怪状的石里蹦跶;我蹲在地上撩江回玩,水花溅了自己同身;我拣小石子玩打水漂,最远得漂四只。

 1    public class NinjectControllerActivator : IControllerActivator
 2     {
 3         public IKernel Kernel { get; private set; }
 4 
 5         public NinjectControllerActivator()
 6         {
 7             this.Kernel = new StandardKernel();
 8         }
 9         public IController Create(RequestContext requestContext, Type controllerType)
10         {
11             return (IController)this.Kernel.TryGet(controllerType);
12         }
13 
14         public void Register<TFrom, TTo>() where TTo : TFrom
15         {
16             this.Kernel.Bind<TFrom>().To<TTo>();
17         }
18     }

圣等人对桂林米粉做了改良,将干捞粉变成了汤粉,再添加了各式浇头。传统的桂林米粉简单纯粹,干捞粉一卖,再因个人口味加入酸笋、酸菜、酸豆角、葱花、香菜、辣椒、炸黄豆、炸花生。大方一点之旅舍会把这些辅料分别就此碗装起来,任客人自行取用。现在桂林米粉为了照看全国各地游人的脾胃,也日益提供了干捞粉和汤粉两种植做法。

银子岩内弯弯绕绕特别多,曲径通幽,人工设计之出游路线经过多年之下结论就成熟。高个人士以钻洞时欲密切注意会不见面逢至条,矮个人士如己,就得放心大胆的左右在移动。

这就是说同样碗粉哟,真香。

我们没有爬山,没有直达岛,也从来不乘船,只是玩象鼻子玩了马拉松。

象鼻山另外的小景点不过是顺带着开出来,供游客观赏打发时间的。它们同别处的山景或岛屿相比,并无呀特色。

如果象鼻山,全世界,仅是如出一辙幢。

————————————————————

高中地理告诉我们,桂林山水乃喀斯特地形。

街上满面沧桑的歌星,孤独地唱卖着和谐之唱片。小摊贩挑在或者好卖的微物,局促之站于路边。

咱错过了银子岩。

咱们失去矣十里画廊。

自我老欣赏那里。

银子岩这溶洞确实地方特别,而且内容丰富。溶洞景点的工作人员一般都喜爱为她配上五彩缤纷的灯光,再指向各种原生态石头的象配上助长的联想。甭管形似非一般,神似总归会有好几。而小景呢,不欲配以名字,就可震撼人心。

材料 // 来源于网络

==================================

自家回忆一所都,回忆一段落时,不如说,是想起当年的自己,一个每当那种状态下,可以活诠释无忧无虑的大团结,一个更为掉不去之傻兮兮的祥和。

我们一定的客栈当阳朔镇达标,尽管当时还未曾共享单车,但我们还是租赁到了车子,一路骑行向大山。离开镇子后,我们的视野瞬间有望。溪水碧草,奇峰峻岭,水墨画一般,缓缓铺陈。两岸青山相对出,可惜没有孤帆,只来同样赞助抓在大学尾巴的大学生在奔突,呼朋引伴。

西街