using JsonRPC4.Common.Tools; using JsonRPC4.Router; using JsonRPC4.Router.Abstractions; using JsonRPC4.Router.Defaults; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; namespace JsonRPC4.Builder { public static class BuilderExtensions { public static IRpcBuilder AddJsonRpc(this IServiceCollection serviceCollection) { if (serviceCollection == null) { throw new ArgumentNullException("serviceCollection"); } serviceCollection.AddSingleton(new RpcServicesMarker()); serviceCollection.TryAddScoped(); serviceCollection.TryAddScoped(); serviceCollection.TryAddScoped(); serviceCollection.TryAddScoped(); serviceCollection.TryAddScoped(); serviceCollection.TryAddScoped(); AuthorizationServiceCollectionExtensions.AddAuthorizationCore(serviceCollection.AddRouting()); return new RpcBuilder(serviceCollection); } public static IApplicationBuilder UseJsonRpc(this IApplicationBuilder app) { if (app == null) { throw new ArgumentNullException("app"); } return app.UseJsonRpcWithBaseController(); } public static IApplicationBuilder UseJsonRpcWithBaseController(this IApplicationBuilder app) { if (app == null) { throw new ArgumentNullException("app"); } return app.UseJsonRpc(delegate (RpcEndpointBuilder builder) { Type baseControllerType = typeof(T); foreach (Type item in (IEnumerable)(from t in Assembly.GetEntryAssembly().GetReferencedAssemblies().Select(Assembly.Load) .SelectMany((Assembly x) => x.DefinedTypes) .Concat(Assembly.GetEntryAssembly().DefinedTypes) where !t.IsAbstract && (t == baseControllerType || t.IsSubclassOf(baseControllerType)) select t)) { builder.AddControllerWithDefaultPath(item); } }); } public static IApplicationBuilder UseJsonRpc(this IApplicationBuilder app, Action builder) { if (app == null) { throw new ArgumentNullException("app"); } if (builder == null) { throw new ArgumentNullException("builder"); } RpcEndpointBuilder rpcEndpointBuilder = new RpcEndpointBuilder(); builder(rpcEndpointBuilder); return app.UseJsonRpc(rpcEndpointBuilder.Resolve()); } public static IApplicationBuilder UseJsonRpc(this IApplicationBuilder app, IRpcMethodProvider methodProvider) { if (app == null) { throw new ArgumentNullException("app"); } if (methodProvider == null) { throw new ArgumentNullException("methodProvider"); } if (app.ApplicationServices.GetService() == null) { throw new InvalidOperationException("AddJsonRpc() needs to be called in the ConfigureServices method."); } RpcHttpRouter router = new RpcHttpRouter(methodProvider); return app.UseRouter(router); } } }