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
/
ServiceFilterAttribute.cs
74 lines (64 loc) · 2.5 KB
/
ServiceFilterAttribute.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
// 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.Diagnostics;
using Microsoft.AspNetCore.Mvc.Core;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.AspNetCore.Mvc
{
/// <summary>
/// A filter that finds another filter in an <see cref="IServiceProvider"/>.
/// </summary>
/// <remarks>
/// <para>
/// Primarily used in <see cref="M:FilterCollection.AddService"/> calls.
/// </para>
/// <para>
/// Similar to the <see cref="TypeFilterAttribute"/> in that both use constructor injection. Use
/// <see cref="TypeFilterAttribute"/> instead if the filter is not itself a service.
/// </para>
/// </remarks>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
[DebuggerDisplay("ServiceFilter: Type={ServiceType} Order={Order}")]
public class ServiceFilterAttribute : Attribute, IFilterFactory, IOrderedFilter
{
/// <summary>
/// Instantiates a new <see cref="ServiceFilterAttribute"/> instance.
/// </summary>
/// <param name="type">The <see cref="Type"/> of filter to find.</param>
public ServiceFilterAttribute(Type type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
ServiceType = type;
}
/// <inheritdoc />
public int Order { get; set; }
/// <summary>
/// Gets the <see cref="Type"/> of filter to find.
/// </summary>
public Type ServiceType { get; }
/// <inheritdoc />
public bool IsReusable { get; set; }
/// <inheritdoc />
public IFilterMetadata CreateInstance(IServiceProvider serviceProvider)
{
if (serviceProvider == null)
{
throw new ArgumentNullException(nameof(serviceProvider));
}
var service = serviceProvider.GetRequiredService(ServiceType);
var filter = service as IFilterMetadata;
if (filter == null)
{
throw new InvalidOperationException(Resources.FormatFilterFactoryAttribute_TypeMustImplementIFilter(
typeof(ServiceFilterAttribute).Name,
typeof(IFilterMetadata).Name));
}
return filter;
}
}
}