This repository has been archived by the owner on Dec 14, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
ControllerActivatorProvider.cs
90 lines (76 loc) · 3.17 KB
/
ControllerActivatorProvider.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
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Reflection;
using Microsoft.AspNetCore.Mvc.Core;
using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.AspNetCore.Mvc.Controllers
{
/// <summary>
/// Provides methods to create an MVC controller.
/// </summary>
public class ControllerActivatorProvider : IControllerActivatorProvider
{
private static readonly Action<ControllerContext, object> _dispose = Dispose;
private readonly Func<ControllerContext, object> _controllerActivatorCreate;
private readonly Action<ControllerContext, object> _controllerActivatorRelease;
public ControllerActivatorProvider(IControllerActivator controllerActivator)
{
if (controllerActivator == null)
{
throw new ArgumentNullException(nameof(controllerActivator));
}
// Compat: Delegate to controllerActivator if it's not the default implementation.
if (controllerActivator.GetType() != typeof(DefaultControllerActivator))
{
_controllerActivatorCreate = controllerActivator.Create;
_controllerActivatorRelease = controllerActivator.Release;
}
}
public Func<ControllerContext, object> CreateActivator(ControllerActionDescriptor descriptor)
{
if (descriptor == null)
{
throw new ArgumentNullException(nameof(descriptor));
}
var controllerType = descriptor.ControllerTypeInfo?.AsType();
if (controllerType == null)
{
throw new ArgumentException(Resources.FormatPropertyOfTypeCannotBeNull(
nameof(descriptor.ControllerTypeInfo),
nameof(descriptor)),
nameof(descriptor));
}
if (_controllerActivatorCreate != null)
{
return _controllerActivatorCreate;
}
var typeActivator = ActivatorUtilities.CreateFactory(controllerType, Type.EmptyTypes);
return controllerContext => typeActivator(controllerContext.HttpContext.RequestServices, arguments: null);
}
public Action<ControllerContext, object> CreateReleaser(ControllerActionDescriptor descriptor)
{
if (descriptor == null)
{
throw new ArgumentNullException(nameof(descriptor));
}
if (_controllerActivatorRelease != null)
{
return _controllerActivatorRelease;
}
if (typeof(IDisposable).GetTypeInfo().IsAssignableFrom(descriptor.ControllerTypeInfo))
{
return _dispose;
}
return null;
}
private static void Dispose(ControllerContext context, object controller)
{
if (controller == null)
{
throw new ArgumentNullException(nameof(controller));
}
((IDisposable)controller).Dispose();
}
}
}