-
Notifications
You must be signed in to change notification settings - Fork 0
/
AppDomainTypeFinder.cs
320 lines (273 loc) · 12 KB
/
AppDomainTypeFinder.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
318
319
320
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Text.RegularExpressions;
namespace NetPro.TypeFinder
{
/// <summary>
///应用程序域内 循环类型查找(在bin目录中)
/// </summary>
public class AppDomainTypeFinder : ITypeFinder
{
#region Fields
private readonly bool _ignoreReflectionErrors = true;
private readonly INetProFileProvider _fileProvider;
#endregion
#region Ctor
public AppDomainTypeFinder(INetProFileProvider fileProvider = null)
{
_fileProvider = fileProvider ?? CoreHelper.DefaultFileProvider;
}
#endregion
#region Utilities
/// <summary>
/// Iterates all assemblies in the AppDomain and if it's name matches the configured patterns add it to our list.
/// </summary>
/// <param name="addedAssemblyNames"></param>
/// <param name="assemblies"></param>
private void AddAssembliesInAppDomain(List<string> addedAssemblyNames, List<Assembly> assemblies)
{
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
if (!Matches(assembly.FullName))
continue;
if (addedAssemblyNames.Contains(assembly.FullName))
continue;
assemblies.Add(assembly);
addedAssemblyNames.Add(assembly.FullName);
}
}
/// <summary>
/// Adds specifically configured assemblies.
/// </summary>
/// <param name="addedAssemblyNames"></param>
/// <param name="assemblies"></param>
protected virtual void AddConfiguredAssemblies(List<string> addedAssemblyNames, List<Assembly> assemblies)
{
foreach (var assemblyName in AssemblyNames)
{
var assembly = Assembly.Load(assemblyName);
if (addedAssemblyNames.Contains(assembly.FullName))
continue;
assemblies.Add(assembly);
addedAssemblyNames.Add(assembly.FullName);
}
}
/// <summary>
/// Check if a dll is one of the shipped dlls that we know don't need to be investigated.
/// </summary>
/// <param name="assemblyFullName">
/// The name of the assembly to check.
/// </param>
/// <returns>
/// True if the assembly should be loaded into Nop.
/// </returns>
public virtual bool Matches(string assemblyFullName)
{
return !Matches(assemblyFullName, AssemblySkipLoadingPattern)
&& Matches(assemblyFullName, AssemblyRestrictToLoadingPattern);
}
/// <summary>
/// Check if a dll is one of the shipped dlls that we know don't need to be investigated.
/// </summary>
/// <param name="assemblyFullName">
/// The assembly name to match.
/// </param>
/// <param name="pattern">
/// The regular expression pattern to match against the assembly name.
/// </param>
/// <returns>
/// True if the pattern matches the assembly name.
/// </returns>
protected virtual bool Matches(string assemblyFullName, string pattern)
{
return Regex.IsMatch(assemblyFullName, pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
}
/// <summary>
/// Makes sure matching assemblies in the supplied folder are loaded in the app domain.
/// </summary>
/// <param name="directoryPath">
/// The physical path to a directory containing dlls to load in the app domain.
/// </param>
protected virtual void LoadMatchingAssemblies(string directoryPath)
{
var loadedAssemblyNames = new List<string>();
foreach (var a in GetAssemblies())
{
loadedAssemblyNames.Add(a.FullName);
}
if (!_fileProvider.DirectoryExists(directoryPath))
{
return;
}
foreach (var dllPath in _fileProvider.GetFiles(directoryPath, "*.dll"))
{
try
{
var an = AssemblyName.GetAssemblyName(dllPath);
if (Matches(an.FullName) && !loadedAssemblyNames.Contains(an.FullName))
{
App.Load(an);
}
//old loading stuff
//Assembly a = Assembly.ReflectionOnlyLoadFrom(dllPath);
//if (Matches(a.FullName) && !loadedAssemblyNames.Contains(a.FullName))
//{
// App.Load(a.FullName);
//}
}
catch (BadImageFormatException ex)
{
Trace.TraceError(ex.ToString());
}
}
}
/// <summary>
/// Does type implement generic?
/// </summary>
/// <param name="type"></param>
/// <param name="openGeneric"></param>
/// <returns></returns>
protected virtual bool DoesTypeImplementOpenGeneric(Type type, Type openGeneric)
{
try
{
var genericTypeDefinition = openGeneric.GetGenericTypeDefinition();
foreach (var implementedInterface in type.FindInterfaces((objType, objCriteria) => true, null))
{
if (!implementedInterface.IsGenericType)
continue;
if (genericTypeDefinition.IsAssignableFrom(implementedInterface.GetGenericTypeDefinition()))
return true;
}
return false;
}
catch
{
return false;
}
}
#endregion
#region Methods
/// <summary>
/// Find classes of type
/// </summary>
/// <typeparam name="T">Type</typeparam>
/// <param name="onlyConcreteClasses">A value indicating whether to find only concrete classes</param>
/// <returns>Result</returns>
public IEnumerable<Type> FindClassesOfType<T>(bool onlyConcreteClasses = true)
{
return FindClassesOfType(typeof(T), onlyConcreteClasses);
}
/// <summary>
/// Find classes of type
/// </summary>
/// <param name="assignTypeFrom">Assign type from</param>
/// <param name="onlyConcreteClasses">A value indicating whether to find only concrete classes</param>
/// <returns>Result</returns>
/// <returns></returns>
public IEnumerable<Type> FindClassesOfType(Type assignTypeFrom, bool onlyConcreteClasses = true)
{
return FindClassesOfType(assignTypeFrom, GetAssemblies(), onlyConcreteClasses);
}
/// <summary>
/// Find classes of type
/// </summary>
/// <typeparam name="T">Type</typeparam>
/// <param name="assemblies">Assemblies</param>
/// <param name="onlyConcreteClasses">A value indicating whether to find only concrete classes</param>
/// <returns>Result</returns>
public IEnumerable<Type> FindClassesOfType<T>(IEnumerable<Assembly> assemblies, bool onlyConcreteClasses = true)
{
return FindClassesOfType(typeof(T), assemblies, onlyConcreteClasses);
}
/// <summary>
/// Find classes of type
/// </summary>
/// <param name="assignTypeFrom">Assign type from</param>
/// <param name="assemblies">Assemblies</param>
/// <param name="onlyConcreteClasses">A value indicating whether to find only concrete classes</param>
/// <returns>Result</returns>
public IEnumerable<Type> FindClassesOfType(Type assignTypeFrom, IEnumerable<Assembly> assemblies, bool onlyConcreteClasses = true)
{
var result = new List<Type>();
try
{
foreach (var a in assemblies)
{
Type[] types = null;
try
{
types = a.GetTypes();
}
catch
{
//Entity Framework 6 doesn't allow getting types (throws an exception)
if (!_ignoreReflectionErrors)
{
throw;
}
}
if (types == null)
continue;
foreach (var t in types)
{
if (!assignTypeFrom.IsAssignableFrom(t) && (!assignTypeFrom.IsGenericTypeDefinition || !DoesTypeImplementOpenGeneric(t, assignTypeFrom)))
continue;
if (t.IsInterface)
continue;
if (onlyConcreteClasses)
{
if (t.IsClass && !t.IsAbstract)
{
result.Add(t);
}
}
else
{
result.Add(t);
}
}
}
}
catch (ReflectionTypeLoadException ex)
{
var msg = string.Empty;
foreach (var e in ex.LoaderExceptions)
msg += e.Message + Environment.NewLine;
var fail = new Exception(msg, ex);
Debug.WriteLine(fail.Message, fail);
throw fail;
}
return result;
}
/// <summary>
/// Gets the assemblies related to the current implementation.
/// </summary>
/// <returns>A list of assemblies</returns>
public virtual IList<Assembly> GetAssemblies()
{
var addedAssemblyNames = new List<string>();
var assemblies = new List<Assembly>();
if (LoadAppDomainAssemblies)
AddAssembliesInAppDomain(addedAssemblyNames, assemblies);
AddConfiguredAssemblies(addedAssemblyNames, assemblies);
return assemblies;
}
#endregion
#region Properties
/// <summary>The app domain to look for types in.</summary>
public virtual AppDomain App => AppDomain.CurrentDomain;
/// <summary>Gets or sets whether Nop should iterate assemblies in the app domain when loading Nop types. Loading patterns are applied when loading these assemblies.</summary>
public bool LoadAppDomainAssemblies { get; set; } = true;
/// <summary>Gets or sets assemblies loaded a startup in addition to those loaded in the AppDomain.</summary>
public IList<string> AssemblyNames { get; set; } = new List<string>();
/// <summary>Gets the pattern for dlls that we know don't need to be investigated.</summary>
public string AssemblySkipLoadingPattern { get; set; } = "^System|^mscorlib|^Microsoft|^AjaxControlToolkit|^Antlr3|^Autofac|^AutoMapper|^Castle|^ComponentArt|^CppCodeProvider|^DotNetOpenAuth|^EntityFramework|^EPPlus|^FluentValidation|^ImageResizer|^itextsharp|^log4net|^MaxMind|^MbUnit|^MiniProfiler|^Mono.Math|^MvcContrib|^Newtonsoft|^NHibernate|^nunit|^Org.Mentalis|^PerlRegex|^QuickGraph|^Recaptcha|^Remotion|^RestSharp|^Rhino|^Telerik|^Iesi|^TestDriven|^TestFu|^UserAgentStringLibrary|^VJSharpCodeProvider|^WebActivator|^WebDev|^WebGrease";
/// <summary>Gets or sets the pattern for dll that will be investigated. For ease of use this defaults to match all but to increase performance you might want to configure a pattern that includes assemblies and your own.</summary>
/// <remarks>If you change this so that Nop assemblies aren't investigated (e.g. by not including something like "^Nop|..." you may break core functionality.</remarks>
public string AssemblyRestrictToLoadingPattern { get; set; } = ".*";
#endregion
}
}