Пример #1
0
        static Runtime()
        {
            ServiceCollection = new ServiceCollection();
            CommandingDependencyResolverAdapter adapter = new CommandingDependencyResolverAdapter(
                (fromType, toInstance) => ServiceCollection.AddSingleton(fromType, toInstance),
                (fromType, toType) => ServiceCollection.AddTransient(fromType, toType),
                (resolveType) => ServiceProvider.GetService(resolveType)
                );

            // Find the configuration implementation
            (IFunctionAppConfiguration configuration, ICommandRegistry commandRegistry) = LocateConfiguration(adapter);

            // Register internal implementations
            RegisterInternalImplementations();

            // Invoke the builder process
            FunctionHostBuilder builder         = CreateBuilderFromConfiguration(commandRegistry, configuration);
            FunctionBuilder     functionBuilder = (FunctionBuilder)builder.FunctionBuilder;

            SetupAuthorization(builder, functionBuilder);

            RegisterTimerCommandFactories(ServiceCollection, builder.FunctionDefinitions);

            ServiceProvider = ServiceCollection.BuildServiceProvider();
            builder.ServiceProviderCreatedAction?.Invoke(ServiceProvider);
        }
Пример #2
0
        private static void ConfigureCommanding(CloudQueue queue, out ICommandDispatcher dispatcher, out IAzureStorageCommandQueueProcessorFactory listenerFactory)
        {
            ServiceCollection serviceCollection = new ServiceCollection();
            CommandingDependencyResolverAdapter dependencyResolver = serviceCollection.GetCommandingDependencyResolver(() => _serviceProvider);
            ICommandRegistry registry = dependencyResolver.AddCommanding();

            dependencyResolver.AddQueues(
                (msg, cmd, ex) =>
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(msg);
            },
                (msg, cmd, ex) =>
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine(msg);
            },
                (msg, cmd, ex) =>
            {
                Console.ForegroundColor = ConsoleColor.Blue;
                Console.WriteLine(msg);
            })
            .AddAzureStorageCommanding();

            registry
            .Register <OutputWorldToConsoleCommandHandler>(1000, dispatcherFactoryFunc: queue.CreateCommandDispatcherFactory())
            .Register <OutputBigglesToConsoleCommandHandler>();

            _serviceProvider = serviceCollection.BuildServiceProvider();
            dispatcher       = _serviceProvider.GetService <ICommandDispatcher>();
            listenerFactory  = _serviceProvider.GetService <IAzureStorageCommandQueueProcessorFactory>();
        }
Пример #3
0
        public FunctionCompiler(Assembly configurationSourceAssembly,
                                string outputBinaryFolder,
                                bool outputProxiesJson,
                                TargetEnum target,
                                IAssemblyCompiler assemblyCompiler = null,
                                ITriggerReferenceProvider triggerReferenceProvider = null)
        {
            _configurationSourceAssembly = configurationSourceAssembly;
            _outputBinaryFolder          = outputBinaryFolder;
            _outputProxiesJson           = outputProxiesJson;
            _target            = target;
            _serviceCollection = new ServiceCollection();
            CommandingDependencyResolverAdapter adapter = new CommandingDependencyResolverAdapter(
                (fromType, toInstance) => _serviceCollection.AddSingleton(fromType, toInstance),
                (fromType, toType) => _serviceCollection.AddTransient(fromType, toType),
                (resolveType) => null // we never resolve during compilation
                );

            _commandRegistry          = adapter.AddCommanding();
            _assemblyCompiler         = assemblyCompiler ?? new AssemblyCompiler();
            _triggerReferenceProvider = triggerReferenceProvider ?? new TriggerReferenceProvider();
            _jsonCompiler             = new JsonCompiler();
            _proxiesJsonCompiler      = new ProxiesJsonCompiler();
            _openApiCompiler          = new OpenApiCompiler();
        }
Пример #4
0
        public RuntimeInstance(Assembly functionAppConfigurationAssembly,
                               Action <IServiceCollection, ICommandRegistry> beforeServiceProviderBuild,
                               Action <IServiceProvider, ICommandRegistry> afterServiceProviderBuild)
        {
            // Find the configuration implementation and service collection
            IFunctionAppConfiguration configuration     = LocateConfiguration(functionAppConfigurationAssembly);
            IContainerProvider        containerProvider =
                // ReSharper disable once SuspiciousTypeConversion.Global - externally provided
                (configuration as IContainerProvider) ?? new DefaultContainerProvider();

            ServiceCollection = containerProvider.CreateServiceCollection();
            CommandingDependencyResolverAdapter adapter = new CommandingDependencyResolverAdapter(
                (fromType, toInstance) => ServiceCollection.AddSingleton(fromType, toInstance),
                (fromType, toType) => ServiceCollection.AddTransient(fromType, toType),
                (resolveType) => ServiceProvider.GetService(resolveType)
                );

            ICommandRegistry commandRegistry;

            // ReSharper disable once SuspiciousTypeConversion.Global - externally provided
            if (configuration is ICommandingConfigurator commandingConfigurator)
            {
                commandRegistry = commandingConfigurator.AddCommanding(adapter);
            }
            else
            {
                CommandingRuntime commandingRuntime = new CommandingRuntime();
                commandRegistry = commandingRuntime.AddCommanding(adapter);
            }

            // Register internal implementations
            RegisterInternalImplementations();

            // Invoke the builder process
            FunctionHostBuilder builder = CreateBuilderFromConfiguration(commandRegistry, configuration);

            Builder = builder;
            FunctionBuilder functionBuilder = (FunctionBuilder)builder.FunctionBuilder;

            SetupAuthorization(builder, functionBuilder);

            RegisterCoreDependencies(builder.FunctionDefinitions);

            RegisterTimerCommandFactories(builder.FunctionDefinitions);

            RegisterHttpDependencies(builder.FunctionDefinitions);

            RegisterCosmosDependencies(builder.FunctionDefinitions);

            beforeServiceProviderBuild?.Invoke(ServiceCollection, commandRegistry);
            ServiceProvider = containerProvider.CreateServiceProvider(ServiceCollection);
            afterServiceProviderBuild?.Invoke(ServiceProvider, commandRegistry);

            builder.ServiceProviderCreatedAction?.Invoke(ServiceProvider);
        }
Пример #5
0
        public Form1()
        {
            InitializeComponent();
            IServiceCollection serviceCollection          = new ServiceCollection();
            ICommandingDependencyResolverAdapter resolver = new CommandingDependencyResolverAdapter((type, instance) => serviceCollection.AddSingleton(type, instance),
                                                                                                    (type, impl) => serviceCollection.AddTransient(type, impl),
                                                                                                    type => _serviceProvider.GetService(type));
            ICommandRegistry registry = resolver.AddCommanding();

            registry.Register <GetTextCommandHandler>();
            _serviceProvider = serviceCollection.BuildServiceProvider();
            _dispatcher      = _serviceProvider.GetService <ICommandDispatcher>();
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Configure a dependency resolver adapter around IServiceCollection and add the commanding
            // system to the service collection
            ICommandingDependencyResolverAdapter commandingAdapter =
                new CommandingDependencyResolverAdapter(
                    (fromType, toInstance) => services.AddSingleton(fromType, toInstance),
                    (fromType, toType) => services.AddTransient(fromType, toType),
                    (resolveType) => ServiceProvider.GetService(resolveType)
                    );
            ICommandRegistry commandRegistry = commandingAdapter.AddCommanding();

            services
            .AddApplication(commandRegistry)
            // We replace the default command dispatcher with one that understands how to translate validation responses into REST respones
            .Replace(new ServiceDescriptor(typeof(ICommandDispatcher), typeof(ApplicationErrorAwareCommandDispatcher), ServiceLifetime.Transient))
            // Add the MVC framework
            // NOTE: The FakeClaimsProvider should be REMOVED from production code. To aid in the example it adds a UserId claim into the pipeline
            .AddMvc(mvc => mvc.Filters.Add(new FakeClaimsProvider()))
            // Configure our REST endpoints based on commands
            .AddAspNetCoreCommanding(cfg => cfg
                                     // first setup a default controller route - optional, we've added versioning
                                     .DefaultControllerRoute("/api/v1/[controller]")
                                     // configure our controller and actions
                                     .Controller("Posts", controller => controller
                                                 .Action <GetPostQuery>(HttpMethod.Get, "{Id}")
                                                 .Action <GetPostsQuery, FromQueryAttribute>(HttpMethod.Get)
                                                 .Action <CreatePostCommand>(HttpMethod.Post)
                                                 )
                                     // setup the system so that any property called AuthenticatedUserId will be mapped from
                                     // the claim UserId
                                     .Claims(mapping => mapping.MapClaimToPropertyName("UserId", "AuthenticatedUserId"))
                                     )
            // Add a validation system that is separated from command / type definition
            .AddFluentValidation();

            // Configure swagger
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "Headless Blog API", Version = "v1"
                });
                // Add the commanding specific configuration to Swagger - note this is only required
                // if you have properties marked [SecurityProperty] that you wish to hide from the API
                // definition
                c.AddAspNetCoreCommanding();
            });
        }
Пример #7
0
        private static ICommandDispatcher Configure()
        {
            IServiceCollection serviceCollection = new ServiceCollection();
            CommandingDependencyResolverAdapter dependencyResolver = serviceCollection.GetCommandingDependencyResolver(() => _serviceProvider);
            Options options = new Options
            {
                MetricCollectionEnabled = false, // set to false to compare like for like
                DisableCorrelationIds   = true,  // as a comparison to mediatr we disable correlation IDs
                Reset = true                     // we reset the registry because we allow repeat runs, in a normal app this isn't required
            };

            dependencyResolver.AddCommanding(options)
            .Register <SimpleHandler>();
            _serviceProvider = serviceCollection.BuildServiceProvider();
            return(_serviceProvider.GetService <ICommandDispatcher>());
        }
Пример #8
0
        static ICommandDispatcher Configure()
        {
            Uri uri = new Uri("http://localhost:52933/api/personalDetails");
            ServiceCollection serviceCollection = new ServiceCollection();
            CommandingDependencyResolverAdapter dependencyResolver = serviceCollection.GetCommandingDependencyResolver(() => _serviceProvider);

            ICommandRegistry registry = dependencyResolver.AddCommanding();

            dependencyResolver.AddHttpCommanding();
            _serviceProvider = serviceCollection.BuildServiceProvider();

            registry.Register <UpdatePersonalDetailsCommand, UpdateResult>(HttpCommandDispatcherFactory.Create(uri, HttpMethod.Put));

            ICommandDispatcher dispatcher = _serviceProvider.GetService <ICommandDispatcher>();

            return(dispatcher);
        }
Пример #9
0
        public Compiler(Assembly configurationSourceAssembly,
                        string outputBinaryFolder,
                        ICompilerLog compilerLog)
        {
            _configurationSourceAssembly = configurationSourceAssembly;
            _outputBinaryFolder          = outputBinaryFolder;
            _compilerLog       = compilerLog;
            _serviceCollection = new ServiceCollection();
            CommandingDependencyResolverAdapter adapter = new CommandingDependencyResolverAdapter(
                (fromType, toInstance) => _serviceCollection.AddSingleton(fromType, toInstance),
                (fromType, toType) => _serviceCollection.AddTransient(fromType, toType),
                (resolveType) => null // we never resolve during compilation
                );

            _commandRegistry          = adapter.AddCommanding();
            _triggerReferenceProvider = new TriggerReferenceProvider();
        }
Пример #10
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Configure the commanding mediator
            CommandingDependencyResolverAdapter adapter = new CommandingDependencyResolverAdapter(
                (fromType, toInstance) => services.AddSingleton(fromType, toInstance),
                (fromType, toType) => services.AddTransient(fromType, toType),
                (resolveTo) => ServiceProvider.GetService(resolveTo));
            ICommandRegistry commandRegistry = adapter.AddCommanding();

            services.Replace(new ServiceDescriptor(typeof(ICommandDispatcher), typeof(TelemetryDispatcher), ServiceLifetime.Transient));

            commandRegistry
            .AddNotificationClient(Configuration["notifications:client:serviceBusConnectionString"])
            .AddProductClient(new Uri(Configuration["products:client:getProductQuery"]));

            // Configure our in process subsystems
            services
            .AddCartApplication(commandRegistry);

            // Configure a REST API
            services
            // For demo purposes we inject some claims without relying on an external provider
            .AddMvc(options => options.Filters.Add <SetClaimsForDemoFilter>())
            // Configure a REST API based around our commands
            .AddAspNetCoreCommanding(cfg => cfg
                                     .Claims(claimsMapper => claimsMapper.MapClaimToPropertyName("UserId", "AuthenticatedUserId"))
                                     .Controller("Email", controller => controller
                                                 .Action <SendEmailCommand>(HttpMethod.Post))
                                     .Controller("Cart", controller => controller
                                                 .Action <AddToCartCommand>(HttpMethod.Put))
                                     )
            // Add the FluentValidation system
            .AddFluentValidation();

            // Configure Swagger
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "Decomposed Application API v1", Version = "v1"
                });
                c.AddAspNetCoreCommanding();
            });
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            CommandingDependencyResolverAdapter resolver = new CommandingDependencyResolverAdapter(
                (fromType, toInstance) => services.AddSingleton(fromType, toInstance),
                (fromType, toType) => services.AddTransient(fromType, toType),
                (resolveTo) => _serviceProvider.GetService(resolveTo));

            ICommandRegistry registry = resolver.AddCommanding();

            registry.Register <UpdatePropertyValueCommandHandler>();
            registry.Register <GetPropertyValueQueryHandler>();
            registry.Register <GetMessageQueryHandler>();

            services
            .AddMvc(cfg => cfg.Filters.Add <ClaimsInjectionFilter>())
            .AddAspNetCoreCommanding(cfg =>
            {
                cfg
                // Define RESTful controllers and actions based on commands
                .Controller("PropertyValue",
                            attributes => attributes.Attribute <AuthorizeAttribute>(),
                            actions => actions
                            .Action <GetPropertyValueQuery>(HttpMethod.Get)
                            .Action <UpdatePropertyValueCommand>(HttpMethod.Put))
                .Controller("Message", actions => { actions.Action <GetMessageQuery>(HttpMethod.Get); })
                // Configure claims to automatically populate properties on commands
                .Claims(mapping =>
                {
                    mapping
                    .MapClaimToCommandProperty <GetPropertyValueQuery>("UserId", cmd => cmd.MisspelledUserId)
                    .MapClaimToPropertyName("UserId", "UserId");
                });
            });

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "My API", Version = "v1"
                });
                c.AddAspNetCoreCommanding();
            });
        }
        protected AbstractDispatchTestBase(Action <ICommandRegistry, CustomDispatcher> registrations)
        {
            var serviceCollection = new ServiceCollection();
            var resolver          = new CommandingDependencyResolverAdapter(
                (type, instance) => serviceCollection.AddSingleton(type, instance),
                (type, impl) => serviceCollection.AddTransient(type, impl),
                type => ServiceProvider.GetService(type)
                );

            CommandingConfiguration = new CommandingRuntime();
            var registry = CommandingConfiguration.AddCommanding(resolver);

            CommandTracer = new CommandTracer();
            serviceCollection.AddSingleton(CommandTracer);
            CustomDispatcher = new CustomDispatcher();
            CustomExecuter   = new CustomExecuter();

            registrations(registry, CustomDispatcher);
            ServiceProvider = serviceCollection.BuildServiceProvider();
            Dispatcher      = ServiceProvider.GetRequiredService <ICommandDispatcher>();
        }
        private static IServiceBusCommandQueueProcessorFactory ConfigureForDequeue()
        {
            if (_dequeueServiceProvider == null)
            {
                IServiceCollection serviceCollection         = new ServiceCollection();
                CommandingDependencyResolverAdapter resolver = new CommandingDependencyResolverAdapter(
                    (fromType, toInstance) => serviceCollection.AddSingleton(fromType, toInstance),
                    (fromType, toType) => serviceCollection.AddTransient(fromType, toType),
                    (resolveType) => _dispatchServiceProvider.GetService(resolveType));
                ICommandRegistry commandRegistry = resolver.AddCommanding();
                resolver.AddQueues().AddAzureServiceBus();

                // register our command to dispatch to a servie bus queue
                commandRegistry.Register <SimpleCommandHandler>();

                _dequeueServiceProvider = serviceCollection.BuildServiceProvider();
            }

            IServiceBusCommandQueueProcessorFactory serviceBusCommandQueueProcessorFactory = _dispatchServiceProvider.GetService <IServiceBusCommandQueueProcessorFactory>();

            return(serviceBusCommandQueueProcessorFactory);
        }
        static void Main(string[] args)
        {
            IServiceProvider serviceProvider = null;

            var serviceCollection = new ServiceCollection()
                                    .AddTransient <CustomCommandExecuter>()
                                    .AddTransient <CustomCommandDispatcher>();

            ICommandRegistry registry = new CommandingDependencyResolverAdapter(
                (type, instance) => serviceCollection.AddSingleton(type, instance),
                (type, impl) => serviceCollection.AddTransient(type, impl),
                type => serviceProvider.GetService(type)
                )
                                        .AddCommanding();

            registry.Register <Command>(() => serviceProvider.GetService <CustomCommandDispatcher>());

            serviceProvider = serviceCollection.BuildServiceProvider();

            serviceProvider.GetService <ICommandDispatcher>().DispatchAsync(new Command());

            Console.ReadKey();
        }
Пример #15
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            CommandingDependencyResolverAdapter adapter = new CommandingDependencyResolverAdapter(
                (fromType, toInstance) => services.AddSingleton(fromType, toInstance),
                (fromType, toType) => services.AddTransient(fromType, toType),
                resolveType => _serviceProvider.GetService(resolveType)
                );

            ICommandRegistry registry = adapter.AddCommanding();

            registry.Discover <Startup>();

            services.AddControllers();

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = false;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(null),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            });

            /*services.AddSwaggerGen(c =>
             * {
             *  c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
             * });*/
        }
        private static ICommandDispatcher ConfigureForDispatchToQueue()
        {
            if (_dispatchServiceProvider == null)
            {
                IServiceCollection serviceCollection         = new ServiceCollection();
                CommandingDependencyResolverAdapter resolver = new CommandingDependencyResolverAdapter(
                    (fromType, toInstance) => serviceCollection.AddSingleton(fromType, toInstance),
                    (fromType, toType) => serviceCollection.AddTransient(fromType, toType),
                    (resolveType) => _dispatchServiceProvider.GetService(resolveType));
                ICommandRegistry commandRegistry = resolver.AddCommanding();
                resolver.AddAzureServiceBus();

                // register our command to dispatch to a servie bus queue
                QueueClient client = new QueueClient(ServiceBusConnectionString, "myqueue");
                commandRegistry.Register <SimpleCommand>(client.CreateCommandDispatcherFactory());

                _dispatchServiceProvider = serviceCollection.BuildServiceProvider();
            }


            ICommandDispatcher dispatcher = _dispatchServiceProvider.GetService <ICommandDispatcher>();

            return(dispatcher);
        }
Пример #17
0
        public RuntimeInstance(Assembly functionAppConfigurationAssembly,
                               Action <IServiceCollection, ICommandRegistry> beforeServiceProviderBuild,
                               IServiceCollection serviceCollection)
        {
            if (serviceCollection == null)
            {
                System.Console.WriteLine("No service collection supplied by runtime");
            }
            ServiceCollection    = serviceCollection ?? new ServiceCollection();
            BuiltServiceProvider = new Lazy <IServiceProvider>(() => ServiceCollection.BuildServiceProvider());

            FunctionAppHostBuilder    appHostBuilder = null;
            IFunctionAppConfiguration configuration  = null;
            IFunctionAppHost          appHost        = ConfigurationLocator.FindFunctionAppHost(functionAppConfigurationAssembly);

            if (appHost != null)
            {
                appHostBuilder = new FunctionAppHostBuilder();
                appHost.Build(appHostBuilder);
                if (appHostBuilder.FunctionAppConfiguration != null)
                {
                    configuration = (IFunctionAppConfiguration)Activator.CreateInstance(appHostBuilder.FunctionAppConfiguration);
                }
            }

            if (configuration == null)
            {
                configuration = ConfigurationLocator.FindConfiguration(functionAppConfigurationAssembly);
            }

            CommandingDependencyResolverAdapter adapter = new CommandingDependencyResolverAdapter(
                (fromType, toInstance) => ServiceCollection.AddSingleton(fromType, toInstance),
                (fromType, toType) => ServiceCollection.AddTransient(fromType, toType),
                resolveType => ServiceProvider.GetService(resolveType)
                );

            ICommandRegistry commandRegistry;

            // ReSharper disable once SuspiciousTypeConversion.Global - externally provided
            if (configuration != null && configuration is ICommandingConfigurator commandingConfigurator)
            {
                commandRegistry = commandingConfigurator.AddCommanding(adapter);
            }
            else
            {
                CommandingRuntime commandingRuntime = new CommandingRuntime();
                commandRegistry = commandingRuntime.AddCommanding(adapter);
            }

            // Register internal implementations
            RegisterInternalImplementations();

            FunctionHostBuilder       builder = null;
            IFunctionCompilerMetadata functionCompilerMetadata = null;
            CompileTargetEnum         compileTarget;

            if (configuration != null)
            {
                // Invoke the builder process
                builder = CreateBuilderFromConfiguration(commandRegistry, configuration);
                if (appHostBuilder != null)
                {
                    builder.Options = appHostBuilder.Options;
                }
                FunctionBuilder functionBuilder = (FunctionBuilder)builder.FunctionBuilder;
                FunctionDefinitions = builder.FunctionDefinitions;
                compileTarget       = builder.Options.HttpTarget;
                SetupAuthorization(builder, functionBuilder);
            }
            else
            {
                functionCompilerMetadata = LocateFunctionCompilerMetadata(functionAppConfigurationAssembly);
                FunctionDefinitions      = functionCompilerMetadata.FunctionDefinitions;
                compileTarget            = functionCompilerMetadata.CompilerOptions.HttpTarget;
            }

            PostBuildPatcher.EnsureFunctionsHaveUniqueNames(FunctionDefinitions);

            RegisterCoreDependencies(builder?.MediatorType ?? typeof(DefaultMediatorDecorator), FunctionDefinitions, compileTarget);

            RegisterTimerCommandFactories(FunctionDefinitions);

            RegisterHttpDependencies(FunctionDefinitions);

            RegisterCosmosDependencies(FunctionDefinitions);

            RegisterOutputBindingDependencies(FunctionDefinitions);


            CreatePluginFunctions(functionCompilerMetadata?.ClaimsMappings, FunctionDefinitions);

            RegisterLoggerIfRequired();
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public virtual void ConfigureServices(IServiceCollection services)
        {
            string storageAccountConnectionString = Configuration["storage:connectionstring"];
            string expensiveOperationQueueName    = Configuration["storage:queuename"];

            CommandingDependencyResolverAdapter resolver = new CommandingDependencyResolverAdapter(
                (fromType, toInstance) => services.AddSingleton(fromType, toInstance),
                (fromType, toType) => services.AddTransient(fromType, toType),
                (resolveTo) => _serviceProvider.GetService(resolveTo));

            // Using an instance of CommandingRuntime rather than the static helpers isolates
            // this commanding infrastructure to this startup class / instance of the web app
            // which means that acceptance tests can be run in parallel with multiple instances
            // of the ASP.Net Core test server.
            ICommandRegistry registry = _commandingRuntime.AddCommanding(resolver);

            //ICommandRegistry registry = resolver.AddCommanding();
            resolver.AddQueues().AddAzureStorageCommanding();

            // Register our command handlers using the discovery approach. Our handlers are in this assembly
            // so we just pass through our assembly
            registry.Discover(typeof(Startup).Assembly);

            // Register our expensive operation command to be sent to a queue
            registry.Register <ExpensiveOperationCommand>(
                CloudQueueDispatcherFactory.Create(storageAccountConnectionString, expensiveOperationQueueName));

            // Register our commands as REST endpoints. This results in an API where the AddCommand, GetPostsQuery,
            // GetPostsForCurrentUserQuery and GetPostQuery are handled as GET requests and executed immediately
            // in process by the registered handlers while the ExpensiveOperationCommand is exposed as a POST operation
            // and results in the command being placed on a queue
            services
            .AddMvc(ConfigureMvcOptions)
            // this block configures our commands to be exposed on endpoints
            .AddAspNetCoreCommanding(cfg => cfg
                                     .Controller("Post", controller => controller
                                                 .Action <GetPostsQuery>(HttpMethod.Get)
                                                 .Action <GetPostQuery, FromRouteAttribute>(HttpMethod.Get, "{PostId}")
                                                 .Action <AddNewPostCommand>(HttpMethod.Post)
                                                 .Action <DeletePostCommand>(HttpMethod.Delete, "{PostId}")
                                                 )
                                     .Controller("Profile", controller => controller
                                                 .Action <GetPostsForCurrentUserQuery>(HttpMethod.Get, "Posts"))
                                     .Controller("ExpensiveOperation", controller => controller
                                                 .Action <ExpensiveOperationCommand>(HttpMethod.Post))
                                     .Controller("SecurityTest", controller => controller
                                                 .Action <SecurityTestCommand>(HttpMethod.Post)
                                                 // we wire this one up with an ActionDefinition model to cover that test path
                                                 .Action(new ActionDefinition
            {
                BindingAttributeType = typeof(FromQueryAttribute),
                CommandType          = typeof(SecurityTestCommand),
                ResultType           = null,
                Route = "asQueryParam",
                Verb  = HttpMethod.Get
            }))
                                     .Claims(ConfigureClaimsMapping)
                                     .LogControllerCode(code =>
            {
                // this will output the code that is compiled for each controller to the debug window
                Debug.WriteLine(code);
            })
                                     );

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "Acceptance Test API", Version = "v1"
                });
                c.AddAspNetCoreCommanding();
            });
        }
Пример #19
0
        public RuntimeInstance(Assembly functionAppConfigurationAssembly,
                               Action <IServiceCollection, ICommandRegistry> beforeServiceProviderBuild,
                               IServiceCollection serviceCollection)
        {
            ServiceCollection    = serviceCollection ?? new ServiceCollection();
            BuiltServiceProvider = new Lazy <IServiceProvider>(() => ServiceCollection.BuildServiceProvider());

            // Find the configuration implementation and service collection
            IFunctionAppConfiguration configuration = LocateConfiguration(functionAppConfigurationAssembly);

            CommandingDependencyResolverAdapter adapter = new CommandingDependencyResolverAdapter(
                (fromType, toInstance) => ServiceCollection.AddSingleton(fromType, toInstance),
                (fromType, toType) => ServiceCollection.AddTransient(fromType, toType),
                resolveType => ServiceProvider.GetService(resolveType)
                );

            ICommandRegistry commandRegistry;

            // ReSharper disable once SuspiciousTypeConversion.Global - externally provided
            if (configuration != null && configuration is ICommandingConfigurator commandingConfigurator)
            {
                commandRegistry = commandingConfigurator.AddCommanding(adapter);
            }
            else
            {
                CommandingRuntime commandingRuntime = new CommandingRuntime();
                commandRegistry = commandingRuntime.AddCommanding(adapter);
            }

            // Register internal implementations
            RegisterInternalImplementations();

            FunctionHostBuilder       builder = null;
            IFunctionCompilerMetadata functionCompilerMetadata = null;

            if (configuration != null)
            {
                // Invoke the builder process
                builder = CreateBuilderFromConfiguration(commandRegistry, configuration);
                FunctionBuilder functionBuilder = (FunctionBuilder)builder.FunctionBuilder;
                FunctionDefinitions = builder.FunctionDefinitions;

                SetupAuthorization(builder, functionBuilder);
            }
            else
            {
                functionCompilerMetadata = LocateFunctionCompilerMetadata(functionAppConfigurationAssembly);
                FunctionDefinitions      = functionCompilerMetadata.FunctionDefinitions;
            }

            RegisterCoreDependencies(FunctionDefinitions);

            RegisterTimerCommandFactories(FunctionDefinitions);

            RegisterHttpDependencies(FunctionDefinitions);

            RegisterCosmosDependencies(FunctionDefinitions);

            CreatePluginFunctions(functionCompilerMetadata?.ClaimsMappings, FunctionDefinitions);

            //beforeServiceProviderBuild?.Invoke(ServiceCollection, commandRegistry);
            //ServiceProvider = containerProvider.CreateServiceProvider(ServiceCollection);
            //afterServiceProviderBuild?.Invoke(ServiceProvider, commandRegistry);

            //builder?.ServiceProviderCreatedAction?.Invoke(ServiceProvider);
        }
Пример #20
0
        private static (IFunctionAppConfiguration, ICommandRegistry) LocateConfiguration(CommandingDependencyResolverAdapter adapter)
        {
            ICommandRegistry          commandRegistry;
            IFunctionAppConfiguration configuration = ConfigurationLocator.FindConfiguration();

            if (configuration is ICommandingConfigurator commandingConfigurator)
            {
                commandRegistry = commandingConfigurator.AddCommanding(adapter);
            }
            else
            {
                commandRegistry = adapter.AddCommanding();
            }

            return(configuration, commandRegistry);
        }