1+ using System ;
2+ using Microsoft . Extensions . DependencyInjection ;
3+ using Microsoft . AspNetCore . Hosting ;
4+ using Microsoft . AspNetCore . NodeServices . HostingModels ;
5+
6+ namespace Microsoft . AspNetCore . NodeServices
7+ {
8+ public static class Configuration
9+ {
10+ public static void AddNodeServices ( this IServiceCollection serviceCollection )
11+ => AddNodeServices ( serviceCollection , new NodeServicesOptions ( ) ) ;
12+
13+ public static void AddNodeServices ( this IServiceCollection serviceCollection , NodeServicesOptions options )
14+ {
15+ serviceCollection . AddSingleton ( typeof ( INodeServices ) , serviceProvider =>
16+ {
17+ // Since this instance is being created through DI, we can access the IHostingEnvironment
18+ // to populate options.ProjectPath if it wasn't explicitly specified.
19+ var hostEnv = serviceProvider . GetRequiredService < IHostingEnvironment > ( ) ;
20+ if ( string . IsNullOrEmpty ( options . ProjectPath ) )
21+ {
22+ options . ProjectPath = hostEnv . ContentRootPath ;
23+ }
24+
25+ return new NodeServicesImpl ( options , ( ) => CreateNodeInstance ( options ) ) ;
26+ } ) ;
27+ }
28+
29+ public static INodeServices CreateNodeServices ( NodeServicesOptions options )
30+ {
31+ return new NodeServicesImpl ( options , ( ) => CreateNodeInstance ( options ) ) ;
32+ }
33+
34+ private static INodeInstance CreateNodeInstance ( NodeServicesOptions options )
35+ {
36+ if ( options . NodeInstanceFactory != null )
37+ {
38+ // If you've explicitly supplied an INodeInstance factory, we'll use that. This is useful for
39+ // custom INodeInstance implementations.
40+ return options . NodeInstanceFactory ( ) ;
41+ }
42+ else
43+ {
44+ // Otherwise we'll construct the type of INodeInstance specified by the HostingModel property,
45+ // which itself has a useful default value.
46+ switch ( options . HostingModel )
47+ {
48+ case NodeHostingModel . Http :
49+ return new HttpNodeInstance ( options . ProjectPath , /* port */ 0 , options . WatchFileExtensions ) ;
50+ case NodeHostingModel . Socket :
51+ return new SocketNodeInstance ( options . ProjectPath , options . WatchFileExtensions ) ;
52+ default :
53+ throw new ArgumentException ( "Unknown hosting model: " + options . HostingModel ) ;
54+ }
55+ }
56+ }
57+ }
58+ }
0 commit comments