This repository has been archived by the owner on Oct 4, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ServiceCollectionExtensions.cs
258 lines (238 loc) · 12.8 KB
/
ServiceCollectionExtensions.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
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
namespace GameMaster
{
using System;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using GameMaster.Commands;
using GameMaster.Constants;
using GameMaster.Repositories;
using GameMaster.Services;
using GameMaster.Settings;
using GameMaster.Translators;
using GameMaster.ViewModels;
using Boilerplate;
using Boilerplate.AspNetCore;
using Boilerplate.AspNetCore.Filters;
using Boilerplate.AspNetCore.Swagger;
using Boilerplate.AspNetCore.Swagger.OperationFilters;
using Boilerplate.AspNetCore.Swagger.SchemaFilters;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Swashbuckle.AspNetCore.Swagger;
public static partial class ServiceCollectionExtensions
{
/// <summary>
/// Configures caching for the application. Registers the <see cref="IDistributedCache"/> and
/// <see cref="IMemoryCache"/> types with the services collection or IoC container. The
/// <see cref="IDistributedCache"/> is intended to be used in cloud hosted scenarios where there is a shared
/// cache, which is shared between multiple instances of the application. Use the <see cref="IMemoryCache"/>
/// otherwise.
/// </summary>
public static IServiceCollection AddCaching(this IServiceCollection services)
{
return services
// Adds IMemoryCache which is a simple in-memory cache.
.AddMemoryCache()
// Adds IDistributedCache which is a distributed cache shared between multiple servers. This adds a
// default implementation of IDistributedCache which is not distributed. See below:
.AddDistributedMemoryCache();
// Uncomment the following line to use the Redis implementation of IDistributedCache. This will
// override any previously registered IDistributedCache service.
// Redis is a very fast cache provider and the recommended distributed cache provider.
// .AddDistributedRedisCache(
// options =>
// {
// });
// Uncomment the following line to use the Microsoft SQL Server implementation of IDistributedCache.
// Note that this would require setting up the session state database.
// Redis is the preferred cache implementation but you can use SQL Server if you don't have an alternative.
// .AddSqlServerCache(
// x =>
// {
// x.ConnectionString = "Server=.;Database=ASPNET5SessionState;Trusted_Connection=True;";
// x.SchemaName = "dbo";
// x.TableName = "Sessions";
// });
}
/// <summary>
/// Configures the settings by binding the contents of the config.json file to the specified Plain Old CLR
/// Objects (POCO) and adding <see cref="IOptions{T}"/> objects to the services collection.
/// </summary>
public static IServiceCollection AddCustomOptions(
this IServiceCollection services,
IConfiguration configuration) =>
services
// Adds IOptions<CacheProfileSettings> to the services container.
.Configure<CacheProfileSettings>(configuration.GetSection(nameof(CacheProfileSettings)));
/// <summary>
/// Adds response compression to enable GZIP compression of responses.
/// </summary>
public static IServiceCollection AddCustomResponseCompression(
this IServiceCollection services,
IConfigurationRoot configuration) =>
services
.AddResponseCompression(
options =>
{
// Add additional MIME types (other than the built in defaults) to enable GZIP compression for.
var responseCompressionSettings = configuration.GetSection<ResponseCompressionSettings>(
nameof(ResponseCompressionSettings));
options.MimeTypes = ResponseCompressionDefaults
.MimeTypes
.Concat(responseCompressionSettings.MimeTypes);
})
.Configure<GzipCompressionProviderOptions>(
options => options.Level = CompressionLevel.Optimal);
/// <summary>
/// Add custom routing settings which determines how URL's are generated.
/// </summary>
public static IServiceCollection AddCustomRouting(this IServiceCollection services) =>
services.AddRouting(
options =>
{
// Improve SEO by stopping duplicate URL's due to case differences or trailing slashes.
// See http://googlewebmastercentral.blogspot.co.uk/2010/04/to-slash-or-not-to-slash.html
// All generated URL's should append a trailing slash.
options.AppendTrailingSlash = true;
// All generated URL's should be lower-case.
options.LowercaseUrls = true;
});
public static IMvcCoreBuilder AddCustomMvcOptions(
this IMvcCoreBuilder builder,
IConfigurationRoot configuration,
IHostingEnvironment hostingEnvironment) =>
builder.AddMvcOptions(
options =>
{
// Controls how controller actions cache content from the config.json file.
var cacheProfileSettings = configuration.GetSection<CacheProfileSettings>();
foreach (var keyValuePair in cacheProfileSettings.CacheProfiles)
{
options.CacheProfiles.Add(keyValuePair);
}
if (hostingEnvironment.IsDevelopment())
{
// Lets you pass a format parameter into the query string to set the response type:
// e.g. ?format=application/json. Good for debugging.
options.Filters.Add(new FormatFilterAttribute());
}
// Check model state for null or invalid models and automatically return a 400 Bad Request.
options.Filters.Add(new ValidateModelStateAttribute());
// Remove string and stream output formatters. These are not useful for an API serving JSON or XML.
options.OutputFormatters.RemoveType<StreamOutputFormatter>();
options.OutputFormatters.RemoveType<StringOutputFormatter>();
// Returns a 406 Not Acceptable if the MIME type in the Accept HTTP header is not valid.
options.ReturnHttpNotAcceptable = true;
});
/// <summary>
/// Adds customized JSON serializer settings.
/// </summary>
public static IMvcCoreBuilder AddCustomJsonOptions(this IMvcCoreBuilder builder) =>
builder.AddJsonOptions(
options =>
{
// Parse dates as DateTimeOffset values by default. You should prefer using DateTimeOffset over
// DateTime everywhere. Not doing so can cause problems with time-zones.
options.SerializerSettings.DateParseHandling = DateParseHandling.DateTimeOffset;
// Output enumeration values as strings in JSON.
options.SerializerSettings.Converters.Add(new StringEnumConverter());
});
/// <summary>
/// Add cross-origin resource sharing (CORS) services and configures named CORS policies. See
/// https://docs.asp.net/en/latest/security/cors.html
/// </summary>
public static IMvcCoreBuilder AddCustomCors(this IMvcCoreBuilder builder) =>
builder.AddCors(
options =>
{
// Create named CORS policies here which you can consume using application.UseCors("PolicyName")
// or a [EnableCors("PolicyName")] attribute on your controller or action.
options.AddPolicy(
CorsPolicyName.AllowAny,
x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
/// <summary>
/// Adds Swagger services and configures the Swagger services.
/// </summary>
public static IServiceCollection AddSwagger(this IServiceCollection services) =>
services.AddSwaggerGen(
options =>
{
var assembly = typeof(Startup).GetTypeInfo().Assembly;
var assemblyProduct = assembly.GetCustomAttribute<AssemblyProductAttribute>().Product;
var assemblyDescription = assembly.GetCustomAttribute<AssemblyDescriptionAttribute>().Description;
options.DescribeAllEnumsAsStrings();
options.DescribeAllParametersInCamelCase();
options.DescribeStringEnumsInCamelCase();
// Add the XML comment file for this assembly, so it's contents can be displayed.
options.IncludeXmlCommentsIfExists(assembly);
// Show an example model for JsonPatchDocument<T>.
options.SchemaFilter<JsonPatchDocumentSchemaFilter>();
// Show an example model for ModelStateDictionary.
options.SchemaFilter<ModelStateDictionarySchemaFilter>();
var info = new Info()
{
Title = assemblyProduct,
Description = assemblyDescription,
Version = "v1"
};
options.SwaggerDoc("v1", info);
});
/// <summary>
/// Adds project commands.
/// </summary>
/// <remarks>
/// AddSingleton - Only one instance is ever created and returned.
/// AddScoped - A new instance is created and returned for each request/response cycle.
/// AddTransient - A new instance is created and returned each time.
/// </remarks>
public static IServiceCollection AddCommands(this IServiceCollection services) =>
services
.AddScoped<IDeleteCarCommand, DeleteCarCommand>()
.AddScoped(x => new Lazy<IDeleteCarCommand>(() => x.GetRequiredService<IDeleteCarCommand>()))
.AddScoped<IGetCarCommand, GetCarCommand>()
.AddScoped(x => new Lazy<IGetCarCommand>(() => x.GetRequiredService<IGetCarCommand>()))
.AddScoped<IGetCarPageCommand, GetCarPageCommand>()
.AddScoped(x => new Lazy<IGetCarPageCommand>(() => x.GetRequiredService<IGetCarPageCommand>()))
.AddScoped<IPatchCarCommand, PatchCarCommand>()
.AddScoped(x => new Lazy<IPatchCarCommand>(() => x.GetRequiredService<IPatchCarCommand>()))
.AddScoped<IPostCarCommand, PostCarCommand>()
.AddScoped(x => new Lazy<IPostCarCommand>(() => x.GetRequiredService<IPostCarCommand>()))
.AddScoped<IPutCarCommand, PutCarCommand>()
.AddScoped(x => new Lazy<IPutCarCommand>(() => x.GetRequiredService<IPutCarCommand>()));
/// <summary>
/// Adds project repositories.
/// </summary>
public static IServiceCollection AddRepositories(this IServiceCollection services) =>
services
.AddScoped<ICarRepository, CarRepository>();
/// <summary>
/// Adds project translators.
/// </summary>
public static IServiceCollection AddTranslators(this IServiceCollection services) =>
services
.AddSingleton<ITranslator<Models.Car, Car>, CarToCarTranslator>()
.AddSingleton<ITranslator<Models.Car, SaveCar>, CarToSaveCarTranslator>()
.AddSingleton<ITranslator<SaveCar, Models.Car>, CarToSaveCarTranslator>();
/// <summary>
/// Adds project services.
/// </summary>
public static IServiceCollection AddServices(this IServiceCollection services) =>
services
.AddSingleton<IClockService, ClockService>();
}
}