forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServiceStackHost.cs
More file actions
502 lines (412 loc) · 17.7 KB
/
Copy pathServiceStackHost.cs
File metadata and controls
502 lines (412 loc) · 17.7 KB
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
// Copyright (c) Service Stack LLC. All Rights Reserved.
// License: https://raw.github.com/ServiceStack/ServiceStack/master/license.txt
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Funq;
using ServiceStack.Caching;
using ServiceStack.Configuration;
using ServiceStack.Formats;
using ServiceStack.Host;
using ServiceStack.Html;
using ServiceStack.IO;
using ServiceStack.Logging;
using ServiceStack.Messaging;
using ServiceStack.Metadata;
using ServiceStack.Serialization;
using ServiceStack.Text;
using ServiceStack.VirtualPath;
using ServiceStack.Web;
namespace ServiceStack
{
public abstract partial class ServiceStackHost
: IAppHost, IFunqlet, IHasContainer, IDisposable
{
private readonly ILog Log = LogManager.GetLogger(typeof(ServiceStackHost));
public static ServiceStackHost Instance { get; protected set; }
public DateTime StartedAt { get; set; }
public DateTime AfterInitAt { get; set; }
public DateTime ReadyAt { get; set; }
protected ServiceStackHost(string serviceName, params Assembly[] assembliesWithServices)
{
this.StartedAt = DateTime.UtcNow;
ServiceName = serviceName;
Container = new Container { DefaultOwner = Owner.External };
ServiceController = CreateServiceController(assembliesWithServices);
ContentTypes = Host.ContentTypes.Instance;
RestPaths = new List<RestPath>();
Routes = new ServiceRoutes(this);
Metadata = new ServiceMetadata(RestPaths);
PreRequestFilters = new List<Action<IHttpRequest, IHttpResponse>>();
GlobalRequestFilters = new List<Action<IHttpRequest, IHttpResponse, object>>();
GlobalResponseFilters = new List<Action<IHttpRequest, IHttpResponse, object>>();
ViewEngines = new List<IViewEngine>();
ServiceExceptionHandlers = new List<HandleServiceExceptionDelegate>();
UncaughtExceptionHandlers = new List<HandleUncaughtExceptionDelegate>();
CatchAllHandlers = new List<HttpHandlerResolverDelegate>();
Plugins = new List<IPlugin> {
new HtmlFormat(),
new CsvFormat(),
new MarkdownFormat(),
new PredefinedRoutesFeature(),
new MetadataFeature(),
};
}
public abstract void Configure(Container container);
protected virtual ServiceController CreateServiceController(params Assembly[] assembliesWithServices)
{
return new ServiceController(this, assembliesWithServices);
//Alternative way to inject Service Resolver strategy
//return new ServiceManager(this,
// new ServiceController(() => assembliesWithServices.ToList().SelectMany(x => x.GetTypes())));
}
public virtual void SetConfig(HostConfig config)
{
Config = config;
}
public virtual ServiceStackHost Init()
{
if (Instance != null)
{
throw new InvalidDataException("ServiceStackHost.Instance has already been set");
}
Service.GlobalResolver = Instance = this;
Config = HostConfig.ResetInstance();
OnConfigLoad();
Config.DebugMode = GetType().Assembly.IsDebugBuild();
if (Config.DebugMode)
{
Plugins.Add(new RequestInfoFeature());
}
ServiceController.Init();
Configure(Container);
if (VirtualPathProvider == null)
{
var pathProviders = new List<IVirtualPathProvider> {
new FileSystemVirtualPathProvider(this, Config.WebHostPhysicalPath)
};
pathProviders.AddRange(Config.EmbeddedResourceSources.Map(x =>
new ResourceVirtualPathProvider(this, x)));
VirtualPathProvider = pathProviders.Count > 1
? new MultiVirtualPathProvider(this, pathProviders.ToArray())
: pathProviders.First();
}
OnAfterInit();
var elapsed = DateTime.UtcNow - this.StartedAt;
Log.InfoFormat("Initializing Application took {0}ms", elapsed.TotalMilliseconds);
return this;
}
public string ServiceName { get; set; }
public ServiceMetadata Metadata { get; set; }
public ServiceController ServiceController { get; set; }
/// <summary>
/// The AppHost.Container. Note: it is not thread safe to register dependencies after AppStart.
/// </summary>
public Container Container { get; set; }
public IServiceRoutes Routes { get; set; }
public List<RestPath> RestPaths = new List<RestPath>();
public Dictionary<Type, Func<IHttpRequest, object>> RequestBinders
{
get { return ServiceController.RequestTypeFactoryMap; }
}
public IContentTypes ContentTypes { get; set; }
public List<Action<IHttpRequest, IHttpResponse>> PreRequestFilters { get; set; }
public List<Action<IHttpRequest, IHttpResponse, object>> GlobalRequestFilters { get; set; }
public List<Action<IHttpRequest, IHttpResponse, object>> GlobalResponseFilters { get; set; }
public List<IViewEngine> ViewEngines { get; set; }
public List<HandleServiceExceptionDelegate> ServiceExceptionHandlers { get; set; }
public List<HandleUncaughtExceptionDelegate> UncaughtExceptionHandlers { get; set; }
public List<HttpHandlerResolverDelegate> CatchAllHandlers { get; set; }
public List<IPlugin> Plugins { get; set; }
public IVirtualPathProvider VirtualPathProvider { get; set; }
/// <summary>
/// Executed immediately before a Service is executed. Use return to change the request DTO used, must be of the same type.
/// </summary>
public virtual object OnPreExecuteServiceFilter(IService service, object request, IHttpRequest httpReq, IHttpResponse httpRes)
{
return request;
}
/// <summary>
/// Executed immediately after a service is executed. Use return to change response used.
/// </summary>
public virtual object OnPostExecuteServiceFilter(IService service, object response, IHttpRequest httpReq, IHttpResponse httpRes)
{
return response;
}
/// <summary>
/// Occurs when the Service throws an Exception.
/// </summary>
public virtual object OnServiceException(IHttpRequest httpReq, object request, Exception ex)
{
object lastError = null;
foreach (var errorHandler in ServiceExceptionHandlers)
{
lastError = errorHandler(httpReq, request, ex) ?? lastError;
}
return lastError;
}
/// <summary>
/// Occurs when an exception is thrown whilst processing a request.
/// </summary>
public virtual void OnUncaughtException(IHttpRequest httpReq, IHttpResponse httpRes, string operationName, Exception ex)
{
if (UncaughtExceptionHandlers.Count > 0)
{
foreach (var errorHandler in UncaughtExceptionHandlers)
{
errorHandler(httpReq, httpRes, operationName, ex);
}
}
else
{
var errorMessage = string.Format("Error occured while Processing Request: {0}", ex.Message);
var statusCode = ex.ToStatusCode();
//httpRes.WriteToResponse always calls .Close in it's finally statement so
//if there is a problem writing to response, by now it will be closed
if (!httpRes.IsClosed)
{
httpRes.WriteErrorToResponse(httpReq, httpReq.ResponseContentType, operationName, errorMessage, ex, statusCode);
}
}
}
private HostConfig config;
public HostConfig Config
{
get
{
return config;
}
set
{
config = value;
OnAfterConfigChanged();
}
}
public virtual void OnConfigLoad()
{
}
// Config has changed
public virtual void OnAfterConfigChanged()
{
config.ServiceEndpointsMetadataConfig = ServiceEndpointsMetadataConfig.Create(config.ServiceStackHandlerFactoryPath);
JsonDataContractSerializer.Instance.UseBcl = config.UseBclJsonSerializers;
JsonDataContractDeserializer.Instance.UseBcl = config.UseBclJsonSerializers;
}
//After configure called
public void OnAfterInit()
{
AfterInitAt = DateTime.UtcNow;
if (config.EnableFeatures != Feature.All)
{
if ((Feature.Xml & config.EnableFeatures) != Feature.Xml)
config.IgnoreFormatsInMetadata.Add("xml");
if ((Feature.Json & config.EnableFeatures) != Feature.Json)
config.IgnoreFormatsInMetadata.Add("json");
if ((Feature.Jsv & config.EnableFeatures) != Feature.Jsv)
config.IgnoreFormatsInMetadata.Add("jsv");
if ((Feature.Csv & config.EnableFeatures) != Feature.Csv)
config.IgnoreFormatsInMetadata.Add("csv");
if ((Feature.Html & config.EnableFeatures) != Feature.Html)
config.IgnoreFormatsInMetadata.Add("html");
if ((Feature.Soap11 & config.EnableFeatures) != Feature.Soap11)
config.IgnoreFormatsInMetadata.Add("soap11");
if ((Feature.Soap12 & config.EnableFeatures) != Feature.Soap12)
config.IgnoreFormatsInMetadata.Add("soap12");
}
if ((Feature.Html & config.EnableFeatures) != Feature.Html)
Plugins.RemoveAll(x => x is HtmlFormat);
if ((Feature.Csv & config.EnableFeatures) != Feature.Csv)
Plugins.RemoveAll(x => x is CsvFormat);
if ((Feature.Markdown & config.EnableFeatures) != Feature.Markdown)
Plugins.RemoveAll(x => x is MarkdownFormat);
if ((Feature.PredefinedRoutes & config.EnableFeatures) != Feature.PredefinedRoutes)
Plugins.RemoveAll(x => x is PredefinedRoutesFeature);
if ((Feature.Metadata & config.EnableFeatures) != Feature.Metadata)
Plugins.RemoveAll(x => x is MetadataFeature);
if ((Feature.RequestInfo & config.EnableFeatures) != Feature.RequestInfo)
Plugins.RemoveAll(x => x is RequestInfoFeature);
if ((Feature.Razor & config.EnableFeatures) != Feature.Razor)
Plugins.RemoveAll(x => x is IRazorPlugin); //external
if ((Feature.ProtoBuf & config.EnableFeatures) != Feature.ProtoBuf)
Plugins.RemoveAll(x => x is IProtoBufPlugin); //external
if ((Feature.MsgPack & config.EnableFeatures) != Feature.MsgPack)
Plugins.RemoveAll(x => x is IMsgPackPlugin); //external
if (config.ServiceStackHandlerFactoryPath != null)
config.ServiceStackHandlerFactoryPath = config.ServiceStackHandlerFactoryPath.TrimStart('/');
var specifiedContentType = config.DefaultContentType; //Before plugins loaded
ConfigurePlugins();
LoadPlugin(Plugins.ToArray());
pluginsLoaded = true;
AfterPluginsLoaded(specifiedContentType);
var registeredCacheClient = TryResolve<ICacheClient>();
using (registeredCacheClient)
{
if (registeredCacheClient == null)
{
Container.Register<ICacheClient>(new MemoryCacheClient());
}
}
var registeredMqService = TryResolve<IMessageService>();
var registeredMqFactory = TryResolve<IMessageFactory>();
if (registeredMqService != null && registeredMqFactory == null)
{
Container.Register(c => registeredMqService.MessageFactory);
}
ReadyAt = DateTime.UtcNow;
}
private void ConfigurePlugins()
{
//Some plugins need to initialize before other plugins are registered.
foreach (var plugin in Plugins)
{
var preInitPlugin = plugin as IPreInitPlugin;
if (preInitPlugin != null)
{
preInitPlugin.Configure(this);
}
}
}
private void AfterPluginsLoaded(string specifiedContentType)
{
if (!String.IsNullOrEmpty(specifiedContentType))
config.DefaultContentType = specifiedContentType;
else if (String.IsNullOrEmpty(config.DefaultContentType))
config.DefaultContentType = MimeTypes.Json;
ServiceController.AfterInit();
}
public T GetPlugin<T>() where T : class, IPlugin
{
return Plugins.FirstOrDefault(x => x is T) as T;
}
private bool pluginsLoaded;
public void AddPlugin(params IPlugin[] plugins)
{
if (pluginsLoaded)
{
LoadPlugin(plugins);
}
else
{
foreach (var plugin in plugins)
{
Plugins.Add(plugin);
}
}
}
public virtual void Release(object instance)
{
try
{
var iocAdapterReleases = Container.Adapter as IRelease;
if (iocAdapterReleases != null)
{
iocAdapterReleases.Release(instance);
}
else
{
var disposable = instance as IDisposable;
if (disposable != null)
disposable.Dispose();
}
}
catch { /*ignore*/ }
}
public virtual void OnEndRequest()
{
foreach (var item in RequestContext.Instance.Items.Values)
{
Release(item);
}
RequestContext.Instance.EndRequest();
}
public virtual void Register<T>(T instance)
{
this.Container.Register(instance);
}
public virtual void RegisterAs<T, TAs>() where T : TAs
{
this.Container.RegisterAutoWiredAs<T, TAs>();
}
public virtual T TryResolve<T>()
{
return this.Container.TryResolve<T>();
}
public virtual T Resolve<T>()
{
return this.Container.Resolve<T>();
}
public virtual IServiceRunner<TRequest> CreateServiceRunner<TRequest>(ActionContext actionContext)
{
//cached per service action
return new ServiceRunner<TRequest>(this, actionContext);
}
public virtual string ResolveAbsoluteUrl(string virtualPath, IHttpRequest httpReq)
{
return httpReq.GetAbsoluteUrl(virtualPath); //Http Listener, TODO: ASP.NET overrides
}
public virtual string ResolvePhysicalPath(string virtualPath, IHttpRequest httpReq)
{
return VirtualPathProvider.CombineVirtualPath(VirtualPathProvider.RootDirectory.RealPath, virtualPath);
}
public virtual IVirtualFile ResolveVirtualFile(string virtualPath, IHttpRequest httpReq)
{
return VirtualPathProvider.GetFile(virtualPath);
}
public virtual IVirtualDirectory ResolveVirtualDirectory(string virtualPath, IHttpRequest httpReq)
{
return virtualPath == VirtualPathProvider.VirtualPathSeparator
? VirtualPathProvider.RootDirectory
: VirtualPathProvider.GetDirectory(virtualPath);
}
public virtual IVirtualNode ResolveVirtualNode(string virtualPath, IHttpRequest httpReq)
{
return (IVirtualNode) ResolveVirtualFile(virtualPath, httpReq)
?? ResolveVirtualDirectory(virtualPath, httpReq);
}
public virtual void LoadPlugin(params IPlugin[] plugins)
{
foreach (var plugin in plugins)
{
try
{
plugin.Register(this);
}
catch (Exception ex)
{
Log.Warn("Error loading plugin " + plugin.GetType().Name, ex);
}
}
}
public virtual object ExecuteService(object requestDto)
{
return ExecuteService(requestDto, RequestAttributes.None);
}
public virtual object ExecuteService(object requestDto, RequestAttributes requestAttributes)
{
return ServiceController.Execute(requestDto, new HttpRequestContext(requestDto, requestAttributes));
}
public virtual void RegisterService(Type serviceType, params string[] atRestPaths)
{
ServiceController.RegisterService(serviceType);
var reqAttr = serviceType.FirstAttribute<DefaultRequestAttribute>();
if (reqAttr != null)
{
foreach (var atRestPath in atRestPaths)
{
this.Routes.Add(reqAttr.RequestType, atRestPath, null);
}
}
}
public virtual void Dispose()
{
if (Container != null)
{
Container.Dispose();
Container = null;
}
Instance = null;
}
}
}