forked from ServiceStackV3/ServiceStack.Contrib
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServiceController.cs
More file actions
288 lines (230 loc) · 8.63 KB
/
Copy pathServiceController.cs
File metadata and controls
288 lines (230 loc) · 8.63 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
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using ServiceStack.Configuration;
using ServiceStack.Logging;
using ServiceStack.Text;
namespace ServiceStack.ServiceHost
{
public class ServiceController
: IServiceController
{
private static readonly ILog Log = LogManager.GetLogger(typeof(ServiceController));
private const string ResponseDtoSuffix = "Response";
public ServiceController()
{
this.AllOperationTypes = new List<Type>();
this.OperationTypes = new List<Type>();
this.ServiceTypes = new HashSet<Type>();
}
readonly Dictionary<Type, Func<IRequestContext, object, object>> requestExecMap
= new Dictionary<Type, Func<IRequestContext, object, object>>();
readonly Dictionary<Type, ServiceAttribute> requestServiceAttrs
= new Dictionary<Type, ServiceAttribute>();
public bool EnableAccessRestrictions { get; set; }
public IList<Type> AllOperationTypes { get; protected set; }
public IList<Type> OperationTypes { get; protected set; }
public HashSet<Type> ServiceTypes { get; protected set; }
public string DefaultOperationsNamespace { get; set; }
public void Register<TReq>(Func<IService<TReq>> invoker)
{
var requestType = typeof(TReq);
Func<IRequestContext, object, object> handlerFn = (requestContext, dto) =>
{
var service = invoker();
InjectRequestContext(service, requestContext);
return ServiceExec<TReq>.Execute(
service, (TReq)dto,
requestContext != null ? requestContext.EndpointAttributes : EndpointAttributes.None);
};
requestExecMap.Add(requestType, handlerFn);
}
public void Register(ITypeFactory serviceFactoryFn, params Assembly[] assembliesWithServices)
{
foreach (var assembly in assembliesWithServices)
{
foreach (var serviceType in assembly.GetTypes())
{
foreach (var service in serviceType.GetInterfaces())
{
if (serviceType.IsAbstract
|| !service.IsGenericType
|| service.GetGenericTypeDefinition() != typeof(IService<>)
) continue;
var requestType = service.GetGenericArguments()[0];
Register(requestType, serviceType, serviceFactoryFn);
this.ServiceTypes.Add(serviceType);
this.AllOperationTypes.Add(requestType);
this.OperationTypes.Add(requestType);
var responseTypeName = requestType.FullName + ResponseDtoSuffix;
var responseType = AssemblyUtils.FindType(responseTypeName);
if (responseType != null)
{
this.AllOperationTypes.Add(responseType);
this.OperationTypes.Add(responseType);
}
Log.DebugFormat("Registering {0} service '{1}' with request '{2}'",
(responseType != null ? "SyncReply" : "OneWay"),
serviceType.Name, requestType.Name);
}
}
}
}
internal class TypeFactoryWrapper : ITypeFactory
{
private readonly Func<Type, object> typeCreator;
public TypeFactoryWrapper(Func<Type, object> typeCreator)
{
this.typeCreator = typeCreator;
}
public object CreateInstance(Type type)
{
return typeCreator(type);
}
}
public void Register(Type requestType, Type serviceType)
{
var handlerFactoryFn = Expression.Lambda<Func<Type, object>>
(
Expression.New(serviceType),
Expression.Parameter(typeof(Type), "serviceType")
).Compile();
Register(requestType, serviceType, new TypeFactoryWrapper(handlerFactoryFn));
}
public void Register(Type requestType, Type serviceType, Func<Type, object> handlerFactoryFn)
{
Register(requestType, serviceType, new TypeFactoryWrapper(handlerFactoryFn));
}
public void Register(Type requestType, Type serviceType, ITypeFactory serviceFactoryFn)
{
var typeFactoryFn = CallServiceExecuteGeneric(requestType, serviceType);
Func<IRequestContext, object, object> handlerFn = (requestContext, dto) =>
{
var service = serviceFactoryFn.CreateInstance(serviceType);
InjectRequestContext(service, requestContext);
var endpointAttrs = requestContext != null
? requestContext.EndpointAttributes
: EndpointAttributes.None;
try
{
return typeFactoryFn(dto, service, endpointAttrs);
}
catch (TargetInvocationException tex)
{
//Mono invokes using reflection
throw tex.InnerException ?? tex;
}
};
try
{
requestExecMap.Add(requestType, handlerFn);
}
catch (ArgumentException)
{
throw new AmbiguousMatchException(
string.Format("Could not register the service '{0}' as another service with the definition of type 'IService<{1}>' already exists.",
serviceType.FullName, requestType.Name));
}
var serviceAttrs = requestType.GetCustomAttributes(typeof(ServiceAttribute), false);
if (serviceAttrs.Length > 0)
{
requestServiceAttrs.Add(requestType, (ServiceAttribute)serviceAttrs[0]);
}
}
private static void InjectRequestContext(object service, IRequestContext requestContext)
{
if (requestContext == null) return;
var serviceRequiresContext = service as IRequiresRequestContext;
if (serviceRequiresContext != null)
{
serviceRequiresContext.RequestContext = requestContext;
}
}
private static Func<object, object, EndpointAttributes, object> CallServiceExecuteGeneric(
Type requestType, Type serviceType)
{
try
{
var requestDtoParam = Expression.Parameter(typeof(object), "requestDto");
var requestDtoStrong = Expression.Convert(requestDtoParam, requestType);
var serviceParam = Expression.Parameter(typeof(object), "serviceObj");
var serviceStrong = Expression.Convert(serviceParam, serviceType);
var attrsParam = Expression.Parameter(typeof(EndpointAttributes), "attrs");
var mi = ServiceExec.GetExecMethodInfo(serviceType, requestType);
Expression callExecute = Expression.Call(
serviceStrong, mi, new Expression[] { serviceStrong, requestDtoStrong, attrsParam });
var executeFunc = Expression.Lambda<Func<object, object, EndpointAttributes, object>>
(callExecute, requestDtoParam, serviceParam, attrsParam).Compile();
return executeFunc;
}
catch (Exception ex)
{
//problems with MONO, using reflection for temp fix
return delegate(object request, object service, EndpointAttributes attrs)
{
var mi = ServiceExec.GetExecMethodInfo(serviceType, requestType);
return mi.Invoke(null, new[] { service, request, attrs });
};
}
}
public object Execute(object dto)
{
return Execute(dto, null);
}
public object Execute(object request, IRequestContext requestContext)
{
var requestType = request.GetType();
if (EnableAccessRestrictions)
{
AssertServiceRestrictions(requestType,
requestContext != null ? requestContext.EndpointAttributes : EndpointAttributes.None);
}
var handlerFn = GetService(requestType);
return handlerFn(requestContext, request);
}
public Func<IRequestContext, object, object> GetService(Type requestType)
{
Func<IRequestContext, object, object> handlerFn;
if (!requestExecMap.TryGetValue(requestType, out handlerFn))
{
throw new NotImplementedException(
string.Format("Unable to resolve service '{0}'", requestType.Name));
}
return handlerFn;
}
public object ExecuteText(string text, IRequestContext requestContext)
{
throw new NotImplementedException();
}
public void AssertServiceRestrictions(Type requestType, EndpointAttributes actualAttributes)
{
ServiceAttribute serviceAttr;
var hasNoAccessRestrictions = !requestServiceAttrs.TryGetValue(requestType, out serviceAttr)
|| serviceAttr.HasNoAccessRestrictions;
if (hasNoAccessRestrictions)
{
return;
}
var failedScenarios = new StringBuilder();
foreach (var requiredScenario in serviceAttr.RestrictAccessToScenarios)
{
var allServiceRestrictionsMet = (requiredScenario & actualAttributes) == actualAttributes;
if (allServiceRestrictionsMet)
{
return;
}
var passed = requiredScenario & actualAttributes;
var failed = requiredScenario & ~(passed);
failedScenarios.AppendFormat("\n -[{0}]", failed);
}
string internalDebugMsg = (EndpointAttributes.InternalNetworkAccess & actualAttributes) != 0
? "\n Unauthorized call was made from: " + actualAttributes
: "";
throw new UnauthorizedAccessException(
string.Format("Could not execute service '{0}', The following restrictions were not met: '{1}'" + internalDebugMsg,
requestType.Name, failedScenarios));
}
}
}