/
ControllerTypeResolver.cs
317 lines (285 loc) · 9.42 KB
/
ControllerTypeResolver.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
using MvcSiteMapProvider.Collections;
using MvcSiteMapProvider.DI;
using MvcSiteMapProvider.Web.Compilation;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web.Mvc;
using System.Web.Routing;
namespace MvcSiteMapProvider.Web.Mvc
{
/// <summary>
/// ControllerTypeResolver class
/// </summary>
[ExcludeFromAutoRegistration]
public class ControllerTypeResolver
: IControllerTypeResolver
{
public ControllerTypeResolver(
IEnumerable<string> areaNamespacesToIgnore,
RouteCollection routes,
IControllerBuilder controllerBuilder,
IBuildManager buildManager
)
{
if (areaNamespacesToIgnore == null)
throw new ArgumentNullException("areaNamespacesToIgnore");
if (routes == null)
throw new ArgumentNullException("routes");
if (controllerBuilder == null)
throw new ArgumentNullException("controllerBuilder");
if (buildManager == null)
throw new ArgumentNullException("buildManager");
this.areaNamespacesToIgnore = areaNamespacesToIgnore;
this.routes = routes;
this.controllerBuilder = controllerBuilder;
this.buildManager = buildManager;
Cache = new ThreadSafeDictionary<string, Type>();
}
protected readonly IEnumerable<string> areaNamespacesToIgnore;
protected readonly RouteCollection routes;
protected readonly IControllerBuilder controllerBuilder;
protected readonly IBuildManager buildManager;
private readonly object synclock = new object();
/// <summary>
/// Gets or sets the cache.
/// </summary>
/// <value>The cache.</value>
protected ThreadSafeDictionary<string, Type> Cache { get; private set; }
/// <summary>
/// Gets or sets the assembly cache.
/// </summary>
/// <value>The assembly cache.</value>
protected Dictionary<string, ILookup<string, Type>> AssemblyCache { get; private set; }
#region IControllerTypeResolver Members
/// <summary>
/// Resolves the type of the controller.
/// </summary>
/// <param name="areaName">Name of the area.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <returns>Controller type</returns>
public Type ResolveControllerType(string areaName, string controllerName)
{
// Is the type cached?
string cacheKey = areaName + "_" + controllerName;
if (Cache.ContainsKey(cacheKey))
{
return Cache[cacheKey];
}
// Find controller details
IEnumerable<string> areaNamespaces = FindNamespacesForArea(areaName, this.routes);
string area = areaName;
string controller = controllerName;
// Find controller type
Type controllerType;
HashSet<string> namespaces = null;
if (areaNamespaces != null)
{
areaNamespaces = (from ns in areaNamespaces
where ns != "Elmah.Mvc"
where !this.areaNamespacesToIgnore.Contains(ns)
select ns).ToList();
if (areaNamespaces.Any())
{
namespaces = new HashSet<string>(areaNamespaces, StringComparer.OrdinalIgnoreCase);
if (string.IsNullOrEmpty(areaName))
{
namespaces = new HashSet<string>(namespaces.Union(this.controllerBuilder.DefaultNamespaces, StringComparer.OrdinalIgnoreCase), StringComparer.OrdinalIgnoreCase);
}
}
}
else if (this.controllerBuilder.DefaultNamespaces.Count > 0)
{
namespaces = this.controllerBuilder.DefaultNamespaces;
}
controllerType = GetControllerTypeWithinNamespaces(area, controller, namespaces);
// Cache the result
Cache.Add(cacheKey, controllerType);
// Return
return controllerType;
}
#endregion
/// <summary>
/// Finds the namespaces for area.
/// </summary>
/// <param name="area">The area.</param>
/// <param name="routes">The routes.</param>
/// <returns>
/// A namespaces for area represented as a <see cref="string"/> instance
/// </returns>
protected virtual IEnumerable<string> FindNamespacesForArea(string area, RouteCollection routes)
{
var namespacesForArea = new List<string>();
var namespacesCommon = new List<string>();
foreach (var route in routes.OfType<Route>().Where(r => r.DataTokens != null && r.DataTokens["Namespaces"] != null))
{
// search for area-based namespaces
if (route.DataTokens["area"] != null && route.DataTokens["area"].ToString().Equals(area, StringComparison.OrdinalIgnoreCase))
namespacesForArea.AddRange((IEnumerable<string>)route.DataTokens["Namespaces"]);
else if (route.DataTokens["area"] == null)
namespacesCommon.AddRange((IEnumerable<string>)route.DataTokens["Namespaces"]);
}
if (namespacesForArea.Count > 0)
{
return namespacesForArea;
}
else if (namespacesCommon.Count > 0)
{
return namespacesCommon;
}
return null;
}
/// <summary>
/// Inits the assembly cache.
/// </summary>
private void InitAssemblyCache()
{
if (AssemblyCache == null)
{
lock (synclock)
{
if (AssemblyCache == null)
{
List<Type> controllerTypes = GetListOfControllerTypes();
var groupedByName = controllerTypes.GroupBy(
t => t.Name.Substring(0, t.Name.IndexOf("Controller")),
StringComparer.OrdinalIgnoreCase);
AssemblyCache = groupedByName.ToDictionary(
g => g.Key,
g => g.ToLookup(t => t.Namespace ?? string.Empty, StringComparer.OrdinalIgnoreCase),
StringComparer.OrdinalIgnoreCase);
}
}
}
}
/// <summary>
/// Gets the list of controller types.
/// </summary>
/// <returns></returns>
protected virtual List<Type> GetListOfControllerTypes()
{
IEnumerable<Type> typesSoFar = Type.EmptyTypes;
ICollection assemblies = this.buildManager.GetReferencedAssemblies();
foreach (Assembly assembly in assemblies)
{
Type[] typesInAsm;
try
{
typesInAsm = assembly.GetTypes();
}
catch (ReflectionTypeLoadException ex)
{
typesInAsm = ex.Types;
}
typesSoFar = typesSoFar.Concat(typesInAsm);
}
return typesSoFar.Where(t => t != null && t.IsClass && t.IsPublic && !t.IsAbstract && t.Name.IndexOf("Controller", StringComparison.OrdinalIgnoreCase) != -1 && typeof(IController).IsAssignableFrom(t)).ToList();
}
/// <summary>
/// Determines whether namespace matches the specified requested namespace.
/// </summary>
/// <param name="requestedNamespace">The requested namespace.</param>
/// <param name="targetNamespace">The target namespace.</param>
/// <returns>
/// <c>true</c> if is namespace matches the specified requested namespace; otherwise, <c>false</c>.
/// </returns>
private static bool IsNamespaceMatch(string requestedNamespace, string targetNamespace)
{
// degenerate cases
if (requestedNamespace == null)
{
return false;
}
else if (requestedNamespace.Length == 0)
{
return true;
}
if (!requestedNamespace.EndsWith(".*", StringComparison.OrdinalIgnoreCase))
{
// looking for exact namespace match
return string.Equals(requestedNamespace, targetNamespace, StringComparison.OrdinalIgnoreCase);
}
else
{
// looking for exact or sub-namespace match
requestedNamespace = requestedNamespace.Substring(0, requestedNamespace.Length - ".*".Length);
if (!targetNamespace.StartsWith(requestedNamespace, StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (requestedNamespace.Length == targetNamespace.Length)
{
// exact match
return true;
}
else if (targetNamespace[requestedNamespace.Length] == '.')
{
// good prefix match, e.g. requestedNamespace = "Foo.Bar" and targetNamespace = "Foo.Bar.Baz"
return true;
}
else
{
// bad prefix match, e.g. requestedNamespace = "Foo.Bar" and targetNamespace = "Foo.Bar2"
return false;
}
}
}
/// <summary>
/// Gets the controller type within namespaces.
/// </summary>
/// <param name="area">The area.</param>
/// <param name="controller">The controller.</param>
/// <param name="namespaces">The namespaces.</param>
/// <returns>
/// A controller type within namespaces represented as a <see cref="Type"/> instance
/// </returns>
protected virtual Type GetControllerTypeWithinNamespaces(string area, string controller, HashSet<string> namespaces)
{
if (string.IsNullOrEmpty(controller) || controller == "")
return null;
InitAssemblyCache();
HashSet<Type> matchingTypes = new HashSet<Type>();
ILookup<string, Type> nsLookup;
if (AssemblyCache.TryGetValue(controller, out nsLookup))
{
// this friendly name was located in the cache, now cycle through namespaces
if (namespaces != null)
{
foreach (string requestedNamespace in namespaces)
{
foreach (var targetNamespaceGrouping in nsLookup)
{
if (IsNamespaceMatch(requestedNamespace, targetNamespaceGrouping.Key))
{
matchingTypes.UnionWith(targetNamespaceGrouping);
}
}
}
}
else
{
// if the namespaces parameter is null, search *every* namespace
foreach (var nsGroup in nsLookup)
{
matchingTypes.UnionWith(nsGroup);
}
}
}
if (matchingTypes.Count == 1)
{
return matchingTypes.First();
}
else if (matchingTypes.Count > 1)
{
string typeNames = Environment.NewLine + Environment.NewLine;
foreach (var matchingType in matchingTypes)
typeNames += matchingType.FullName + Environment.NewLine;
typeNames += Environment.NewLine;
throw new AmbiguousControllerException(string.Format(Resources.Messages.AmbiguousControllerFoundMultipleControllers, controller, typeNames));
}
return null;
}
}
}