forked from NancyFx/Nancy
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathMetadataModule.cs
More file actions
86 lines (75 loc) · 3.09 KB
/
MetadataModule.cs
File metadata and controls
86 lines (75 loc) · 3.09 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
namespace Nancy.Metadata.Modules
{
using System;
using System.Collections.Generic;
using Nancy.Routing;
/// <summary>
/// Base class containing the functionality for obtaining metadata for a given <see cref="RouteDescription"/>.
/// </summary>
public abstract class MetadataModule<TMetadata> : IMetadataModule where TMetadata : class
{
private readonly IDictionary<string, Func<RouteDescription, TMetadata>> metadata;
protected MetadataModule()
{
this.metadata = new Dictionary<string, Func<RouteDescription, TMetadata>>();
}
/// <summary>
/// Gets <see cref="RouteMetadataBuilder"/> for describing routes.
/// </summary>
/// <value>A <see cref="RouteMetadataBuilder"/> instance.</value>
public RouteMetadataBuilder Describe
{
get { return new RouteMetadataBuilder(this); }
}
/// <summary>
/// Gets the <see cref="Type"/> of metadata based on <typeparamref name="TMetadata" />.
/// </summary>
public Type MetadataType
{
get
{
return typeof(TMetadata);
}
}
/// <summary>
/// Returns metadata for the given <see cref="RouteDescription"/>.
/// </summary>
/// <param name="description">The route to obtain metadata for.</param>
/// <returns>An instance of <see cref="MetadataType"/> if one exists, otherwise null.</returns>
public object GetMetadata(RouteDescription description)
{
if (this.metadata.ContainsKey(description.Name))
{
return this.metadata[description.Name].Invoke(description);
}
return null;
}
/// <summary>
/// Helper class for configuring a route metadata handler in a module.
/// </summary>
public class RouteMetadataBuilder
{
private readonly MetadataModule<TMetadata> parentModule;
/// <summary>
/// Initializes a new instance of the <see cref="RouteMetadataBuilder"/> class.
/// </summary>
/// <param name="metadataModule">The <see cref="MetadataModule{TMetadata}"/> that the route is being configured for.</param>
public RouteMetadataBuilder(MetadataModule<TMetadata> metadataModule)
{
this.parentModule = metadataModule;
}
/// <summary>
/// Describes metadata for a route with the specified <paramref name="name"/>.
/// </summary>
/// <value>A delegate that is used to return the route metadata.</value>
public Func<RouteDescription, TMetadata> this[string name]
{
set { this.AddRouteMetadata(name, value); }
}
protected void AddRouteMetadata(string name, Func<RouteDescription, TMetadata> value)
{
this.parentModule.metadata.Add(name, value);
}
}
}
}