-
Notifications
You must be signed in to change notification settings - Fork 20
/
RequestServicesFeatureFactory.cs
59 lines (56 loc) · 2.82 KB
/
RequestServicesFeatureFactory.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
using System;
using System.Linq;
using System.Linq.Expressions;
using Autofac.Integration.AspNetCore.Multitenant.Properties;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.DependencyInjection;
#if NETSTANDARD2_0
using Microsoft.AspNetCore.Hosting.Internal;
#endif
namespace Autofac.Integration.AspNetCore.Multitenant
{
internal static class RequestServicesFeatureFactory
{
private static readonly Lazy<Func<HttpContext, IServiceScopeFactory, IServiceProvidersFeature>> FactoryFunction = new Lazy<Func<HttpContext, IServiceScopeFactory, IServiceProvidersFeature>>(GenerateLambda);
public static IServiceProvidersFeature CreateFeature(HttpContext context, IServiceScopeFactory scopeFactory)
{
return FactoryFunction.Value.Invoke(context, scopeFactory);
}
private static Func<HttpContext, IServiceScopeFactory, IServiceProvidersFeature> GenerateLambda()
{
var constructor = typeof(RequestServicesFeature).GetConstructors().OrderByDescending(ci => ci.GetParameters().Length).First();
var parameterCount = constructor.GetParameters().Length;
var contextParameter = Expression.Parameter(typeof(HttpContext), "context");
var factoryParameter = Expression.Parameter(typeof(IServiceScopeFactory), "factory");
switch (parameterCount)
{
case 1:
// ASP.NET Core through 2.1 has RequestServicesFeature ctor only with scope factory.
var subExpression = Expression.Lambda<Func<IServiceScopeFactory, IServiceProvidersFeature>>(
Expression.Convert(
Expression.New(
constructor,
factoryParameter),
typeof(IServiceProvidersFeature)),
factoryParameter)
.Compile();
return (ctx, factory) => subExpression(factory);
case 2:
// ASP.NET Core 2.1 changed RequestServicesFeature ctor to take context and scope factory.
return Expression.Lambda<Func<HttpContext, IServiceScopeFactory, IServiceProvidersFeature>>(
Expression.Convert(
Expression.New(
constructor,
contextParameter,
factoryParameter),
typeof(IServiceProvidersFeature)),
contextParameter,
factoryParameter)
.Compile();
default:
throw new NotSupportedException(Resources.NoSupportedRequestServicesConstructorFound);
}
}
}
}