public IFaultInjectionTransactionalState <TState> Create <TState>(IFaultInjectionTransactionalStateConfiguration config) where TState : class, new()
        {
            var currentContext = this.contextAccessor.GrainContext;
            TransactionalState <TState> transactionalState = ActivatorUtilities.CreateInstance <TransactionalState <TState> >(currentContext.ActivationServices, new TransactionalStateConfiguration(config), this.contextAccessor);
            FaultInjectionTransactionalState <TState> deactivationTransactionalState = ActivatorUtilities.CreateInstance <FaultInjectionTransactionalState <TState> >(currentContext.ActivationServices, transactionalState, this.contextAccessor);

            deactivationTransactionalState.Participate(currentContext.ObservableLifecycle);
            return(deactivationTransactionalState);
        }
示例#2
0
 private IMigration CreateInstance(Type type)
 {
     return((IMigration)ActivatorUtilities.CreateInstance(_serviceProvider, type));
 }
示例#3
0
        public async Task <T> CreateClientAsync(string name, ApiVersion apiVersion = null)
        {
            var salesforceClient = await this.salesforceClientFactory.CreateClientAsync(name, apiVersion);

            return(ActivatorUtilities.CreateInstance <T>(this.serviceProvider, salesforceClient));
        }
        public void AddService(Type type)
        {
            var instance = ActivatorUtilities.CreateInstance(_game.Services, type);

            _game.Services.AddService(type, instance);
        }
        public void Invoke(InterceptionArgs arg)
        {
            arg.Proceed();

            if (this._action == null)
            {
                var      method     = this._type.GetMethod(this._methodName, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static);
                object[] parameters = (method.GetParameters().Length == 0) ? null : new[] { this._key };
                var      instance   = this._instance;

                if (instance == null)
                {
                    if (method.IsStatic == false)
                    {
                        instance = (this._serviceProvider == null) ? Activator.CreateInstance(this._type) : ActivatorUtilities.CreateInstance(this._serviceProvider, this._type);
                    }
                }

                method.Invoke(instance, parameters);
            }
            else
            {
                this._action();
            }
        }
示例#6
0
 object CreateHandler(Type handlerType)
 {
     return(ActivatorUtilities.GetServiceOrCreateInstance(serviceProvider.CreateScope().ServiceProvider, handlerType));
 }
示例#7
0
        public void ProcessOrder(Cart cart, ShippingDetails shippingInfo)
        {
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddDataProtection();
            var services = serviceCollection.BuildServiceProvider();

            // create an instance of MyClass using the service provider
            var    instance         = ActivatorUtilities.CreateInstance <Encryptor>(services);
            string creditCardNumber = instance.Encrypt(shippingInfo.CreditCard);

            var client = new SmtpClient();

            client.Connect("firstsuperfoods.com", 587, SecureSocketOptions.None);
            client.AuthenticationMechanisms.Remove("XOAUTH2");
            client.Authenticate("*****@*****.**", "xxx");



            StringBuilder body = new StringBuilder()
                                 .AppendLine("A new order has been submitted")
                                 .AppendLine("---")
                                 .AppendLine("Items:");

            foreach (var line in cart.Lines)
            {
                var subtotal = line.Product.Price * line.Quantity;
                body.AppendFormat("{0} x {1} (subtotal: {2:c}  ", line.Quantity,
                                  line.Product.Name,
                                  subtotal);
            }

            body.AppendFormat("  Total order value: {0:c}", cart.ComputeTotalValue())
            .AppendLine("---")
            .AppendLine()
            .AppendLine("Ship to:")
            .AppendLine(shippingInfo.Name)
            .AppendLine(shippingInfo.Phone)
            .AppendLine(shippingInfo.ShippingLine1)
            .AppendLine(shippingInfo.ShippingLine2 ?? "")
            .AppendLine(shippingInfo.ShippingCity)
            .AppendLine(shippingInfo.ShippingState)
            .AppendLine(shippingInfo.ShippingCountry)
            .AppendLine(shippingInfo.ShippingZip)
            .AppendLine()
            .AppendLine("Billing Info:")
            .AppendLine(shippingInfo.NameOnCard)
            .AppendLine("CreditCard:")
            .AppendLine(creditCardNumber)
            .AppendFormat("Expired Month: {0}", shippingInfo.Month)
            .AppendLine()
            .AppendFormat("Expired Year: {0}", shippingInfo.Year)
            .AppendLine()
            .AppendLine(shippingInfo.Line1)
            .AppendLine(shippingInfo.Line2 ?? "")
            .AppendLine(shippingInfo.City)
            .AppendLine(shippingInfo.State)
            .AppendLine(shippingInfo.Country)
            .AppendLine(shippingInfo.Zip);



            var mail = new MimeMessage();

            mail.From.Add(new MailboxAddress("FirstSuperFoods", "*****@*****.**"));
            mail.To.Add(new MailboxAddress("", "*****@*****.**"));
            mail.Subject = "New order submitted!";
            //BodyBuilder bodyBuilder = new BodyBuilder();
            //bodyBuilder.HtmlBody = msg.MessageBody;
            //mail.Body = bodyBuilder.ToMessageBody();
            mail.Body = new TextPart("plain")
            {
                Text = body.ToString()
            };

            client.Send(mail);
            client.Disconnect(true);
        }
示例#8
0
        public Action<IBuilder> LoadStartup(
            string applicationName,
            string environmentName,
            IList<string> diagnosticMessages)
        {
            if (String.IsNullOrEmpty(applicationName))
            {
                return _next.LoadStartup(applicationName, environmentName, diagnosticMessages);
            }

            var assembly = Assembly.Load(new AssemblyName(applicationName));
            if (assembly == null)
            {
                throw new Exception(String.Format("TODO: assembly {0} failed to load message", applicationName));
            }

            var startupName1 = "Startup" + environmentName;
            var startupName2 = "Startup";

            // Check the most likely places first
            var type =
                assembly.GetType(startupName1) ??
                assembly.GetType(applicationName + "." + startupName1) ??
                assembly.GetType(startupName2) ??
                assembly.GetType(applicationName + "." + startupName2);

            if (type == null)
            {
                // Full scan
                var definedTypes = assembly.DefinedTypes.ToList();

                var startupType1 = definedTypes.Where(info => info.Name.Equals(startupName1, StringComparison.Ordinal));
                var startupType2 = definedTypes.Where(info => info.Name.Equals(startupName2, StringComparison.Ordinal));

                var typeInfo = startupType1.Concat(startupType2).FirstOrDefault();
                if (typeInfo != null)
                {
                    type = typeInfo.AsType();
                }
            }

            if (type == null)
            {
                throw new Exception(String.Format("TODO: {0} or {1} class not found in assembly {2}", 
                    startupName1,
                    startupName2,
                    applicationName));
            }

            var configureMethod1 = "Configure" + environmentName;
            var configureMethod2 = "Configure";
            var methodInfo = type.GetTypeInfo().GetDeclaredMethod(configureMethod1);
            if (methodInfo == null)
            {
                methodInfo = type.GetTypeInfo().GetDeclaredMethod(configureMethod2);
            }
            if (methodInfo == null)
            {
                throw new Exception(string.Format("TODO: {0} or {1} method not found",
                    configureMethod1,
                    configureMethod2));
            }

            if (methodInfo.ReturnType != typeof(void))
            {
                throw new Exception(string.Format("TODO: {0} method isn't void-returning.",
                    methodInfo.Name));
            }

            object instance = null;
            if (!methodInfo.IsStatic)
            {
                instance = ActivatorUtilities.GetServiceOrCreateInstance(_services, type);
            }

            return builder =>
            {
                var parameterInfos = methodInfo.GetParameters();
                var parameters = new object[parameterInfos.Length];
                for (var index = 0; index != parameterInfos.Length; ++index)
                {
                    var parameterInfo = parameterInfos[index];
                    if (parameterInfo.ParameterType == typeof(IBuilder))
                    {
                        parameters[index] = builder;
                    }
                    else
                    {
                        try
                        {
                            parameters[index] = _services.GetService(parameterInfo.ParameterType);
                        }
                        catch (Exception ex)
                        {
                            throw new Exception(string.Format(
                                "TODO: Unable to resolve service for startup method {0} {1}",
                                parameterInfo.Name,
                                parameterInfo.ParameterType.FullName));
                        }
                    }
                }
                methodInfo.Invoke(instance, parameters);
            };
        }
示例#9
0
 protected TInvokable GetInvokable <TInvokable>() => ActivatorUtilities.GetServiceOrCreateInstance <TInvokable>(Shared.ServiceProvider);
示例#10
0
        protected override IEventHandler <TEvent> CreateHandler <TEvent>(IServiceScope scope)
        {
            var type = typeof(ProjectionEventHandler <,>).MakeGenericType(_schema.Type, typeof(TEvent));

            return((IEventHandler <TEvent>)ActivatorUtilities.CreateInstance(scope.ServiceProvider, type));
        }
示例#11
0
        private static async Task Main()
        {
            var builder = new ConfigurationBuilder();

            BuildConfig(builder);

            Log.Logger = new LoggerConfiguration()
                         .ReadFrom.Configuration(builder.Build())
                         .Enrich.FromLogContext()
                         .WriteTo.Console()
                         .CreateLogger();

            Log.Logger.Information("Initializing...");

            var host = Host.CreateDefaultBuilder()
                       .ConfigureAppConfiguration((hostContext, configurationBuilder) =>
            {
                var appAssembly =
                    Assembly.Load(new AssemblyName(hostContext.HostingEnvironment.ApplicationName));

                configurationBuilder.AddUserSecrets(appAssembly, true);
            })
                       .ConfigureServices((context, services) =>
            {
                services.AddSingleton <IFacebookService, FacebookService>();
            })
                       .UseSerilog()
                       .Build();

            var configService   = host.Services.GetService <IConfiguration>();
            var facebookService = ActivatorUtilities.CreateInstance <FacebookService>(host.Services);

            Log.Logger.Information("Finished initializing!");

            var accessToken = configService.GetValue <string>("Facebook:AccessToken");

            var accounts = await facebookService.GetAsync <Accounts>(new Dictionary <string, string>
            {
                { "access_token", accessToken }
            });

            Log.Logger.Information($"Posting to page {accounts.Data.Select(x => x.Name).FirstOrDefault()}");

            var pageAccessToken = accounts.Data.Select(x => x.AccessToken).FirstOrDefault();
            var pageId          = accounts.Data.Select(x => x.Id).FirstOrDefault();

            var feed = await facebookService.PostAsync <Feed>(null,
                                                              new Dictionary <string, string>
            {
                { "page-id", pageId }
            },
                                                              new Dictionary <string, string>
            {
                { "access_token", pageAccessToken },
                { "message", $"Test Post Created @ {DateTime.UtcNow:F}" }
            });

            Log.Logger.Information($"Successfully posted with ID {feed.Id}");

            await Task.Delay(Timeout.Infinite);
        }
示例#12
0
 public IFilterMetadata CreateInstance(IServiceProvider serviceProvider)
 {
     return(ActivatorUtilities.CreateInstance <ProblemDetailsResultFilter>(serviceProvider));
 }
示例#13
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var types = (objectType.IsInterface
                ? GetTypes()
                         .Where(p => objectType.IsAssignableFrom(p))
                : GetTypes()
                         .Where(t => t.IsSubclassOf(objectType) || objectType == t)).ToArray();

            Type type;

            var token = JToken.Load(reader);

            if (!(token is JObject jObject))
            {
                return(null);
            }

            if (types.Length == 1)
            {
                type = types[0];
            }
            else if (types.Length == 0)
            {
                throw new SettingsException($"No classes implement {objectType.Name}");
            }
            else
            {
                var classNameProp = jObject.Property("@Name");

                if (classNameProp == null)
                {
                    throw new SettingsException($"Cannot find property @Name")
                          {
                              JToken = jObject
                          }
                }
                ;

                classNameProp.Remove();

                var className = classNameProp.Value.Value <string>();

                type = types.FirstOrDefault(q => q.Name.Equals(className));

                if (type == null)
                {
                    throw new SettingsException($"Cannot find implementation '{className}' of '{objectType.Name}'");
                }
            }

            object result = null;

            if (_serviceProvider != null)
            {
                result = ActivatorUtilities.CreateInstance(_serviceProvider, type);
            }

            if (result == null)
            {
                result = Activator.CreateInstance(type);
            }

            serializer.Populate(jObject.CreateReader(), result);

            return(result);
        }
        private IDictionary <Type, Func <DbContext> > FindContextTypes()
        {
            _reporter.WriteVerbose(DesignStrings.FindingContexts);

            var contexts = new Dictionary <Type, Func <DbContext> >();

            // Look for IDesignTimeDbContextFactory implementations
            _reporter.WriteVerbose(DesignStrings.FindingContextFactories);
            var contextFactories = _startupAssembly.GetConstructibleTypes()
                                   .Where(t => typeof(IDesignTimeDbContextFactory <DbContext>).GetTypeInfo().IsAssignableFrom(t));

            foreach (var factory in contextFactories)
            {
                _reporter.WriteVerbose(DesignStrings.FoundContextFactory(factory.ShortDisplayName()));
                var manufacturedContexts =
                    from i in factory.ImplementedInterfaces
                    where i.GetTypeInfo().IsGenericType &&
                    i.GetGenericTypeDefinition() == typeof(IDesignTimeDbContextFactory <>)
                    select i.GenericTypeArguments[0];
                foreach (var context in manufacturedContexts)
                {
                    _reporter.WriteVerbose(DesignStrings.FoundDbContext(context.ShortDisplayName()));
                    contexts.Add(
                        context,
                        () => CreateContextFromFactory(factory.AsType()));
                }
            }

            // Look for DbContext classes registered in the service provider
            var appServices        = _appServicesFactory.Create(_args);
            var registeredContexts = appServices.GetServices <DbContextOptions>()
                                     .Select(o => o.ContextType);

            foreach (var context in registeredContexts.Where(c => !contexts.ContainsKey(c)))
            {
                _reporter.WriteVerbose(DesignStrings.FoundDbContext(context.ShortDisplayName()));
                contexts.Add(
                    context,
                    FindContextFactory(context)
                    ?? (() => (DbContext)ActivatorUtilities.GetServiceOrCreateInstance(appServices, context)));
            }

            // Look for DbContext classes in assemblies
            _reporter.WriteVerbose(DesignStrings.FindingReferencedContexts);
            var types = _startupAssembly.GetConstructibleTypes()
                        .Concat(_assembly.GetConstructibleTypes())
                        .ToList();
            var contextTypes = types.Where(t => typeof(DbContext).GetTypeInfo().IsAssignableFrom(t)).Select(
                t => t.AsType())
                               .Concat(
                types.Where(t => typeof(Migration).GetTypeInfo().IsAssignableFrom(t))
                .Select(t => t.GetCustomAttribute <DbContextAttribute>()?.ContextType)
                .Where(t => t != null))
                               .Distinct();

            foreach (var context in contextTypes.Where(c => !contexts.ContainsKey(c)))
            {
                _reporter.WriteVerbose(DesignStrings.FoundDbContext(context.ShortDisplayName()));
                contexts.Add(
                    context,
                    FindContextFactory(context) ?? (() =>
                {
                    try
                    {
                        return((DbContext)Activator.CreateInstance(context));
                    }
                    catch (MissingMethodException ex)
                    {
                        throw new OperationException(DesignStrings.NoParameterlessConstructor(context.Name), ex);
                    }
                }));
            }

            return(contexts);
        }
 public static T CreateInstance <T>(this ServiceProvider serviceProvider)
 => ActivatorUtilities.CreateInstance <T>(serviceProvider);
示例#16
0
 public static IStreamProvider Create(IServiceProvider services, string name)
 {
     return(ActivatorUtilities.CreateInstance <SimpleMessageStreamProvider>(services, name,
                                                                            services.GetRequiredService <IOptionsMonitor <SimpleMessageStreamProviderOptions> >().Get(name)));
 }
 public static object CreateInstance(this ServiceProvider serviceProvider, Type instanceType,
                                     params object[] parameters)
 => ActivatorUtilities.CreateInstance(serviceProvider, instanceType, parameters);
 public static Func <StreamId, IStreamDataGenerator <EventData> > CreateFactory(IServiceProvider services)
 {
     return((streamId) => ActivatorUtilities.CreateInstance <SimpleStreamEventDataGenerator>(services, streamId));
 }
示例#19
0
 public void QueueJob <T>() where T : IJob
 {
     QueueJob(sp => ActivatorUtilities.CreateInstance <T>(sp));
 }
示例#20
0
 internal static CustomNameTopologyProvider Create(IServiceProvider services, string name)
 {
     return(ActivatorUtilities.CreateInstance <CustomNameTopologyProvider>(services, name));
 }
示例#21
0
 /// <summary>
 /// Instantiate an instance of the given type.
 /// </summary>
 /// <param name="type"></param>
 /// <returns></returns>
 public virtual object Activate(Type type)
 {
     return(ActivatorUtilities.GetServiceOrCreateInstance(_services, type));
 }
示例#22
0
 internal static ExchangeBasedTopologyProvider Create(IServiceProvider services, string name)
 {
     return(ActivatorUtilities.CreateInstance <ExchangeBasedTopologyProvider>(services, name));
 }
示例#23
0
 public static IGrainStorage Create(IServiceProvider services, string name)
 {
     return(ActivatorUtilities.CreateInstance <MemoryGrainStorage>(services,
                                                                   services.GetRequiredService <IOptionsSnapshot <MemoryGrainStorageOptions> >().Get(name), name));
 }
示例#24
0
        private void UseStartup([DynamicallyAccessedMembers(StartupLinkerOptions.Accessibility)] Type startupType, HostBuilderContext context, IServiceCollection services, object?instance = null)
        {
            var webHostBuilderContext = GetWebHostBuilderContext(context);
            var webHostOptions        = (WebHostOptions)context.Properties[typeof(WebHostOptions)];

            ExceptionDispatchInfo?startupError     = null;
            ConfigureBuilder?     configureBuilder = null;

            try
            {
                // We cannot support methods that return IServiceProvider as that is terminal and we need ConfigureServices to compose
                if (typeof(IStartup).IsAssignableFrom(startupType))
                {
                    throw new NotSupportedException($"{typeof(IStartup)} isn't supported");
                }
                if (StartupLoader.HasConfigureServicesIServiceProviderDelegate(startupType, context.HostingEnvironment.EnvironmentName))
                {
                    throw new NotSupportedException($"ConfigureServices returning an {typeof(IServiceProvider)} isn't supported.");
                }

                instance ??= ActivatorUtilities.CreateInstance(new HostServiceProvider(webHostBuilderContext), startupType);
                context.Properties[_startupKey] = instance;

                // Startup.ConfigureServices
                var configureServicesBuilder = StartupLoader.FindConfigureServicesDelegate(startupType, context.HostingEnvironment.EnvironmentName);
                var configureServices        = configureServicesBuilder.Build(instance);

                configureServices(services);

                // REVIEW: We're doing this in the callback so that we have access to the hosting environment
                // Startup.ConfigureContainer
                var configureContainerBuilder = StartupLoader.FindConfigureContainerDelegate(startupType, context.HostingEnvironment.EnvironmentName);
                if (configureContainerBuilder.MethodInfo != null)
                {
                    var containerType = configureContainerBuilder.GetContainerType();
                    // Store the builder in the property bag
                    _builder.Properties[typeof(ConfigureContainerBuilder)] = configureContainerBuilder;

                    var actionType = typeof(Action <,>).MakeGenericType(typeof(HostBuilderContext), containerType);

                    // Get the private ConfigureContainer method on this type then close over the container type
                    var configureCallback = typeof(GenericWebHostBuilder).GetMethod(nameof(ConfigureContainerImpl), BindingFlags.NonPublic | BindingFlags.Instance) !
                                            .MakeGenericMethod(containerType)
                                            .CreateDelegate(actionType, this);

                    // _builder.ConfigureContainer<T>(ConfigureContainer);
                    typeof(IHostBuilder).GetMethod(nameof(IHostBuilder.ConfigureContainer)) !
                    .MakeGenericMethod(containerType)
                    .InvokeWithoutWrappingExceptions(_builder, new object[] { configureCallback });
                }

                // Resolve Configure after calling ConfigureServices and ConfigureContainer
                configureBuilder = StartupLoader.FindConfigureDelegate(startupType, context.HostingEnvironment.EnvironmentName);
            }
            catch (Exception ex) when(webHostOptions.CaptureStartupErrors)
            {
                startupError = ExceptionDispatchInfo.Capture(ex);
            }

            // Startup.Configure
            services.Configure <GenericWebHostServiceOptions>(options =>
            {
                options.ConfigureApplication = app =>
                {
                    // Throw if there was any errors initializing startup
                    startupError?.Throw();

                    // Execute Startup.Configure
                    if (instance != null && configureBuilder != null)
                    {
                        configureBuilder.Build(instance)(app);
                    }
                };
            });
        }
示例#25
0
        public static ILogViewAdaptorFactory Create(IServiceProvider services, string name)
        {
            var optionsMonitor = services.GetRequiredService <IOptionsMonitor <CustomStorageLogConsistencyOptions> >();

            return(ActivatorUtilities.CreateInstance <LogConsistencyProvider>(services, optionsMonitor.Get(name)));
        }
示例#26
0
 protected T ResolveCollection <T>() => ActivatorUtilities.CreateInstance <T>(_serviceProvider);
示例#27
0
        internal static void AddDefaultServices(IApplicationPartManager applicationPartManager, IServiceCollection services)
        {
            services.AddOptions();

            services.AddTransient <IConfigurationValidator, EndpointOptionsValidator>();

            // Options logging
            services.TryAddSingleton(typeof(IOptionFormatter <>), typeof(DefaultOptionsFormatter <>));
            services.TryAddSingleton(typeof(IOptionFormatterResolver <>), typeof(DefaultOptionsFormatterResolver <>));

            // Register system services.
            services.TryAddSingleton <ILocalSiloDetails, LocalSiloDetails>();
            services.TryAddSingleton <ISiloHost, SiloHost>();
            services.TryAddTransient <ILifecycleSubject, LifecycleSubject>();
            services.TryAddSingleton <SiloLifecycleSubject>();
            services.TryAddFromExisting <ISiloLifecycleSubject, SiloLifecycleSubject>();
            services.TryAddFromExisting <ISiloLifecycle, SiloLifecycleSubject>();
            services.AddSingleton <SiloOptionsLogger>();
            services.AddFromExisting <ILifecycleParticipant <ISiloLifecycle>, SiloOptionsLogger>();
            services.PostConfigure <SiloMessagingOptions>(options =>
            {
                //
                // Assign environment specific defaults post configuration if user did not configured otherwise.
                //

                if (options.SiloSenderQueues == 0)
                {
                    options.SiloSenderQueues = Environment.ProcessorCount;
                }

                if (options.GatewaySenderQueues == 0)
                {
                    options.GatewaySenderQueues = Environment.ProcessorCount;
                }
            });
            services.TryAddSingleton <TelemetryManager>();
            services.TryAddFromExisting <ITelemetryProducer, TelemetryManager>();

            services.TryAddSingleton <IAppEnvironmentStatistics, AppEnvironmentStatistics>();
            services.TryAddSingleton <IHostEnvironmentStatistics, NoOpHostEnvironmentStatistics>();
            services.TryAddSingleton <SiloStatisticsManager>();
            services.TryAddFromExisting <IStatisticsManager, SiloStatisticsManager>();
            services.TryAddSingleton <ApplicationRequestsStatisticsGroup>();
            services.TryAddSingleton <StageAnalysisStatisticsGroup>();
            services.TryAddSingleton <SchedulerStatisticsGroup>();
            services.TryAddSingleton <SerializationStatisticsGroup>();
            services.TryAddSingleton <OverloadDetector>();

            services.TryAddSingleton <FallbackSystemTarget>();
            services.TryAddSingleton <LifecycleSchedulingSystemTarget>();

            services.AddLogging();
            services.TryAddSingleton <ITimerRegistry, TimerRegistry>();
            services.TryAddSingleton <IReminderRegistry, ReminderRegistry>();
            services.AddTransient <IConfigurationValidator, ReminderOptionsValidator>();
            services.TryAddSingleton <GrainRuntime>();
            services.TryAddSingleton <IGrainRuntime, GrainRuntime>();
            services.TryAddSingleton <IGrainCancellationTokenRuntime, GrainCancellationTokenRuntime>();
            services.AddTransient <CancellationSourcesExtension>();
            services.AddTransientKeyedService <Type, IGrainExtension>(typeof(ICancellationSourcesExtension), (sp, _) => sp.GetRequiredService <CancellationSourcesExtension>());
            services.TryAddSingleton <OrleansTaskScheduler>();
            services.TryAddSingleton <GrainFactory>(sp => sp.GetService <InsideRuntimeClient>().ConcreteGrainFactory);
            services.TryAddSingleton <GrainInterfaceTypeToGrainTypeResolver>();
            services.TryAddFromExisting <IGrainFactory, GrainFactory>();
            services.TryAddFromExisting <IInternalGrainFactory, GrainFactory>();
            services.TryAddSingleton <IGrainReferenceRuntime, GrainReferenceRuntime>();
            services.TryAddSingleton <GrainReferenceActivator>();
            services.AddSingleton <IGrainReferenceActivatorProvider, ImrGrainReferenceActivatorProvider>();
            services.AddSingleton <IGrainReferenceActivatorProvider, UntypedGrainReferenceActivatorProvider>();
            services.AddSingleton <IConfigureGrainContextProvider, MayInterleaveConfiguratorProvider>();
            services.AddSingleton <IConfigureGrainTypeComponents, ReentrantSharedComponentsConfigurator>();
            services.TryAddSingleton <ImrRpcProvider>();
            services.TryAddSingleton <ImrGrainMethodInvokerProvider>();
            services.TryAddSingleton <GrainReferenceSerializer>();
            services.TryAddSingleton <GrainReferenceKeyStringConverter>();
            services.AddSingleton <GrainVersionManifest>();
            services.TryAddSingleton <GrainBindingsResolver>();
            services.TryAddSingleton <GrainTypeComponentsResolver>();
            services.TryAddSingleton <ActivationDirectory>();
            services.AddSingleton <ActivationCollector>();
            services.AddFromExisting <IActivationCollector, ActivationCollector>();

            // Directory
            services.TryAddSingleton <LocalGrainDirectory>();
            services.TryAddFromExisting <ILocalGrainDirectory, LocalGrainDirectory>();
            services.AddSingleton <GrainLocator>();
            services.AddSingleton <GrainLocatorResolver>();
            services.AddSingleton <DhtGrainLocator>(sp => DhtGrainLocator.FromLocalGrainDirectory(sp.GetService <LocalGrainDirectory>()));
            services.AddSingleton <GrainDirectoryResolver>();
            services.AddSingleton <IGrainDirectoryResolver, GenericGrainDirectoryResolver>();
            services.AddSingleton <CachedGrainLocator>();
            services.AddFromExisting <ILifecycleParticipant <ISiloLifecycle>, CachedGrainLocator>();
            services.AddSingleton <ClientGrainLocator>();

            services.TryAddSingleton <MessageCenter>();
            services.TryAddFromExisting <IMessageCenter, MessageCenter>();
            services.TryAddSingleton(FactoryUtility.Create <MessageCenter, Gateway>);
            services.TryAddSingleton <IConnectedClientCollection>(sp => (IConnectedClientCollection)sp.GetRequiredService <MessageCenter>().Gateway ?? new EmptyConnectedClientCollection());
            services.TryAddSingleton <Dispatcher>(sp => sp.GetRequiredService <Catalog>().Dispatcher);
            services.TryAddSingleton <ActivationMessageScheduler>(sp => sp.GetRequiredService <Catalog>().ActivationMessageScheduler);
            services.TryAddSingleton <InsideRuntimeClient>();
            services.TryAddFromExisting <IRuntimeClient, InsideRuntimeClient>();
            services.AddFromExisting <ILifecycleParticipant <ISiloLifecycle>, InsideRuntimeClient>();
            services.TryAddSingleton <IGrainServiceFactory, GrainServiceFactory>();

            services.TryAddSingleton <IFatalErrorHandler, FatalErrorHandler>();

            services.TryAddSingleton <DeploymentLoadPublisher>();

            services.TryAddSingleton <IAsyncTimerFactory, AsyncTimerFactory>();
            services.TryAddSingleton <MembershipTableManager>();
            services.AddFromExisting <IHealthCheckParticipant, MembershipTableManager>();
            services.AddFromExisting <ILifecycleParticipant <ISiloLifecycle>, MembershipTableManager>();
            services.TryAddSingleton <MembershipSystemTarget>();
            services.AddFromExisting <IMembershipService, MembershipSystemTarget>();
            services.TryAddSingleton <IMembershipGossiper, MembershipGossiper>();
            services.TryAddSingleton <IRemoteSiloProber, RemoteSiloProber>();
            services.TryAddSingleton <SiloStatusOracle>();
            services.TryAddFromExisting <ISiloStatusOracle, SiloStatusOracle>();
            services.AddSingleton <ClusterHealthMonitor>();
            services.AddFromExisting <ILifecycleParticipant <ISiloLifecycle>, ClusterHealthMonitor>();
            services.AddFromExisting <IHealthCheckParticipant, ClusterHealthMonitor>();
            services.AddSingleton <ProbeRequestMonitor>();
            services.AddSingleton <LocalSiloHealthMonitor>();
            services.AddFromExisting <ILocalSiloHealthMonitor, LocalSiloHealthMonitor>();
            services.AddFromExisting <ILifecycleParticipant <ISiloLifecycle>, LocalSiloHealthMonitor>();
            services.AddSingleton <MembershipAgent>();
            services.AddFromExisting <ILifecycleParticipant <ISiloLifecycle>, MembershipAgent>();
            services.AddFromExisting <IHealthCheckParticipant, MembershipAgent>();
            services.AddSingleton <MembershipTableCleanupAgent>();
            services.AddFromExisting <ILifecycleParticipant <ISiloLifecycle>, MembershipTableCleanupAgent>();
            services.AddFromExisting <IHealthCheckParticipant, MembershipTableCleanupAgent>();
            services.AddSingleton <SiloStatusListenerManager>();
            services.AddFromExisting <ILifecycleParticipant <ISiloLifecycle>, SiloStatusListenerManager>();
            services.AddSingleton <ClusterMembershipService>();
            services.TryAddFromExisting <IClusterMembershipService, ClusterMembershipService>();
            services.AddFromExisting <ILifecycleParticipant <ISiloLifecycle>, ClusterMembershipService>();

            services.TryAddSingleton <ClientDirectory>();
            services.AddFromExisting <ILocalClientDirectory, ClientDirectory>();
            services.AddFromExisting <ILifecycleParticipant <ISiloLifecycle>, ClientDirectory>();

            services.TryAddSingleton <SiloProviderRuntime>();
            services.TryAddFromExisting <IProviderRuntime, SiloProviderRuntime>();

            services.TryAddSingleton <MessageFactory>();

            services.TryAddSingleton(FactoryUtility.Create <GrainDirectoryPartition>);

            // Placement
            services.AddSingleton <IConfigurationValidator, ActivationCountBasedPlacementOptionsValidator>();
            services.AddSingleton <PlacementService>();
            services.AddSingleton <PlacementStrategyResolver>();
            services.AddSingleton <PlacementDirectorResolver>();
            services.AddSingleton <IPlacementStrategyResolver, ClientObserverPlacementStrategyResolver>();

            // Configure the default placement strategy.
            services.TryAddSingleton <PlacementStrategy, RandomPlacement>();

            // Placement directors
            services.AddPlacementDirector <RandomPlacement, RandomPlacementDirector>();
            services.AddPlacementDirector <PreferLocalPlacement, PreferLocalPlacementDirector>();
            services.AddPlacementDirector <StatelessWorkerPlacement, StatelessWorkerDirector>();
            services.Replace(new ServiceDescriptor(typeof(StatelessWorkerPlacement), sp => new StatelessWorkerPlacement(), ServiceLifetime.Singleton));
            services.AddPlacementDirector <ActivationCountBasedPlacement, ActivationCountPlacementDirector>();
            services.AddPlacementDirector <HashBasedPlacement, HashBasedPlacementDirector>();
            services.AddPlacementDirector <ClientObserversPlacement, ClientObserversPlacementDirector>();

            // Activation selectors
            services.AddSingletonKeyedService <Type, IActivationSelector, RandomPlacementDirector>(typeof(RandomPlacement));
            services.AddSingletonKeyedService <Type, IActivationSelector, StatelessWorkerDirector>(typeof(StatelessWorkerPlacement));

            // Versioning
            services.TryAddSingleton <VersionSelectorManager>();
            services.TryAddSingleton <CachedVersionSelectorManager>();
            // Version selector strategy
            if (!services.Any(x => x.ServiceType == typeof(IVersionStore)))
            {
                services.TryAddSingleton <GrainVersionStore>();
                services.AddFromExisting <IVersionStore, GrainVersionStore>();
            }
            services.AddFromExisting <ILifecycleParticipant <ISiloLifecycle>, GrainVersionStore>();
            services.AddSingletonNamedService <VersionSelectorStrategy, AllCompatibleVersions>(nameof(AllCompatibleVersions));
            services.AddSingletonNamedService <VersionSelectorStrategy, LatestVersion>(nameof(LatestVersion));
            services.AddSingletonNamedService <VersionSelectorStrategy, MinimumVersion>(nameof(MinimumVersion));
            // Versions selectors
            services.AddSingletonKeyedService <Type, IVersionSelector, MinimumVersionSelector>(typeof(MinimumVersion));
            services.AddSingletonKeyedService <Type, IVersionSelector, LatestVersionSelector>(typeof(LatestVersion));
            services.AddSingletonKeyedService <Type, IVersionSelector, AllCompatibleVersionsSelector>(typeof(AllCompatibleVersions));

            // Compatibility
            services.TryAddSingleton <CompatibilityDirectorManager>();
            // Compatability strategy
            services.AddSingletonNamedService <CompatibilityStrategy, AllVersionsCompatible>(nameof(AllVersionsCompatible));
            services.AddSingletonNamedService <CompatibilityStrategy, BackwardCompatible>(nameof(BackwardCompatible));
            services.AddSingletonNamedService <CompatibilityStrategy, StrictVersionCompatible>(nameof(StrictVersionCompatible));
            // Compatability directors
            services.AddSingletonKeyedService <Type, ICompatibilityDirector, BackwardCompatilityDirector>(typeof(BackwardCompatible));
            services.AddSingletonKeyedService <Type, ICompatibilityDirector, AllVersionsCompatibilityDirector>(typeof(AllVersionsCompatible));
            services.AddSingletonKeyedService <Type, ICompatibilityDirector, StrictVersionCompatibilityDirector>(typeof(StrictVersionCompatible));

            services.TryAddSingleton <Factory <IGrainRuntime> >(sp => () => sp.GetRequiredService <IGrainRuntime>());

            // Grain activation
            services.TryAddSingleton <Catalog>();
            services.AddFromExisting <IHealthCheckParticipant, Catalog>();
            services.TryAddSingleton <GrainContextActivator>();
            services.AddSingleton <IConfigureGrainTypeComponents, ConfigureDefaultGrainActivator>();
            services.TryAddSingleton <GrainReferenceActivator>();
            services.TryAddSingleton <IGrainContextActivatorProvider, ActivationDataActivatorProvider>();
            services.TryAddSingleton <IGrainContextAccessor, GrainContextAccessor>();
            services.AddSingleton <IncomingRequestMonitor>();
            services.AddFromExisting <ILifecycleParticipant <ISiloLifecycle>, IncomingRequestMonitor>();

            services.TryAddSingleton <IConsistentRingProvider>(
                sp =>
            {
                // TODO: make this not sux - jbragg
                var consistentRingOptions = sp.GetRequiredService <IOptions <ConsistentRingOptions> >().Value;
                var siloDetails           = sp.GetRequiredService <ILocalSiloDetails>();
                var loggerFactory         = sp.GetRequiredService <ILoggerFactory>();
                if (consistentRingOptions.UseVirtualBucketsConsistentRing)
                {
                    return(new VirtualBucketsRingProvider(siloDetails.SiloAddress, loggerFactory, consistentRingOptions.NumVirtualBucketsConsistentRing));
                }

                return(new ConsistentRingProvider(siloDetails.SiloAddress, loggerFactory));
            });

            services.TryAddSingleton(typeof(IKeyedServiceCollection <,>), typeof(KeyedServiceCollection <,>));

            // Serialization
            services.TryAddSingleton <SerializationManager>(sp => ActivatorUtilities.CreateInstance <SerializationManager>(sp,
                                                                                                                           sp.GetRequiredService <IOptions <SiloMessagingOptions> >().Value.LargeMessageWarningThreshold));
            services.TryAddSingleton <ITypeResolver, CachedTypeResolver>();
            services.TryAddSingleton <IFieldUtils, FieldUtils>();

            // Register the ISerializable serializer first, so that it takes precedence
            services.AddSingleton <DotNetSerializableSerializer>();
            services.AddFromExisting <IKeyedSerializer, DotNetSerializableSerializer>();


            services.AddSingleton <ILBasedSerializer>();
            services.AddFromExisting <IKeyedSerializer, ILBasedSerializer>();

            // Transactions
            services.TryAddSingleton <ITransactionAgent, DisabledTransactionAgent>();

            // Application Parts
            services.TryAddSingleton <IApplicationPartManager>(applicationPartManager);
            applicationPartManager.AddApplicationPart(new AssemblyPart(typeof(RuntimeVersion).Assembly)
            {
                IsFrameworkAssembly = true
            });
            applicationPartManager.AddApplicationPart(new AssemblyPart(typeof(Silo).Assembly)
            {
                IsFrameworkAssembly = true
            });
            applicationPartManager.AddFeatureProvider(new BuiltInTypesSerializationFeaturePopulator());
            applicationPartManager.AddFeatureProvider(new AssemblyAttributeFeatureProvider <GrainInterfaceFeature>());
            applicationPartManager.AddFeatureProvider(new AssemblyAttributeFeatureProvider <GrainClassFeature>());
            applicationPartManager.AddFeatureProvider(new AssemblyAttributeFeatureProvider <SerializerFeature>());
            services.AddTransient <IConfigurationValidator, ApplicationPartValidator>();

            // Type metadata
            services.AddSingleton <SiloManifestProvider>();
            services.AddSingleton <GrainClassMap>(sp => sp.GetRequiredService <SiloManifestProvider>().GrainTypeMap);
            services.AddSingleton <GrainTypeResolver>();
            services.AddSingleton <IGrainTypeProvider, AttributeGrainTypeProvider>();
            services.AddSingleton <IGrainTypeProvider, LegacyGrainTypeResolver>();
            services.AddSingleton <GrainPropertiesResolver>();
            services.AddSingleton <GrainInterfaceTypeResolver>();
            services.AddSingleton <IGrainInterfacePropertiesProvider, AttributeGrainInterfacePropertiesProvider>();
            services.AddSingleton <IGrainPropertiesProvider, AttributeGrainPropertiesProvider>();
            services.AddSingleton <IGrainPropertiesProvider, AttributeGrainBindingsProvider>();
            services.AddSingleton <IGrainInterfacePropertiesProvider, TypeNameGrainPropertiesProvider>();
            services.AddSingleton <IGrainPropertiesProvider, TypeNameGrainPropertiesProvider>();
            services.AddSingleton <IGrainPropertiesProvider, ImplementedInterfaceProvider>();
            services.AddSingleton <ClusterManifestProvider>();
            services.AddFromExisting <IClusterManifestProvider, ClusterManifestProvider>();
            services.AddFromExisting <ILifecycleParticipant <ISiloLifecycle>, ClusterManifestProvider>();
            services.AddSingleton <TypeConverter>();

            //Add default option formatter if none is configured, for options which are required to be configured
            services.ConfigureFormatter <SiloOptions>();
            services.ConfigureFormatter <SchedulingOptions>();
            services.ConfigureFormatter <PerformanceTuningOptions>();
            services.ConfigureFormatter <SerializationProviderOptions>();
            services.ConfigureFormatter <ConnectionOptions>();
            services.ConfigureFormatter <SiloMessagingOptions>();
            services.ConfigureFormatter <ClusterMembershipOptions>();
            services.ConfigureFormatter <GrainDirectoryOptions>();
            services.ConfigureFormatter <ActivationCountBasedPlacementOptions>();
            services.ConfigureFormatter <GrainCollectionOptions>();
            services.ConfigureFormatter <GrainVersioningOptions>();
            services.ConfigureFormatter <ConsistentRingOptions>();
            services.ConfigureFormatter <StatisticsOptions>();
            services.ConfigureFormatter <TelemetryOptions>();
            services.ConfigureFormatter <LoadSheddingOptions>();
            services.ConfigureFormatter <EndpointOptions>();
            services.ConfigureFormatter <ClusterOptions>();

            // This validator needs to construct the IMembershipOracle and the IMembershipTable
            // so move it in the end so other validator are called first
            services.AddTransient <IConfigurationValidator, ClusterOptionsValidator>();
            services.AddTransient <IConfigurationValidator, SiloClusteringValidator>();
            services.AddTransient <IConfigurationValidator, DevelopmentClusterMembershipOptionsValidator>();

            // Enable hosted client.
            services.TryAddSingleton <HostedClient>();
            services.AddFromExisting <ILifecycleParticipant <ISiloLifecycle>, HostedClient>();
            services.TryAddSingleton <InternalClusterClient>();
            services.TryAddFromExisting <IInternalClusterClient, InternalClusterClient>();
            services.TryAddFromExisting <IClusterClient, InternalClusterClient>();

            // Enable collection specific Age limits
            services.AddOptions <GrainCollectionOptions>()
            .Configure <IApplicationPartManager>((options, parts) =>
            {
                var grainClasses = new GrainClassFeature();
                parts.PopulateFeature(grainClasses);

                foreach (var grainClass in grainClasses.Classes)
                {
                    var attr = grainClass.ClassType.GetCustomAttribute <CollectionAgeLimitAttribute>();
                    if (attr != null)
                    {
                        var className = TypeUtils.GetFullName(grainClass.ClassType);
                        options.ClassSpecificCollectionAge[className] = attr.Amount;
                    }
                }
            });

            // Validate all CollectionAgeLimit values for the right configuration.
            services.AddTransient <IConfigurationValidator, GrainCollectionOptionsValidator>();

            services.AddTransient <IConfigurationValidator, LoadSheddingValidator>();

            services.TryAddSingleton <ITimerManager, TimerManagerImpl>();

            // persistent state facet support
            services.TryAddSingleton <IPersistentStateFactory, PersistentStateFactory>();
            services.TryAddSingleton(typeof(IAttributeToFactoryMapper <PersistentStateAttribute>), typeof(PersistentStateAttributeMapper));

            // Networking
            services.TryAddSingleton <ConnectionCommon>();
            services.TryAddSingleton <ConnectionManager>();
            services.AddSingleton <ILifecycleParticipant <ISiloLifecycle>, ConnectionManagerLifecycleAdapter <ISiloLifecycle> >();
            services.AddSingleton <ILifecycleParticipant <ISiloLifecycle>, SiloConnectionMaintainer>();

            services.AddSingletonKeyedService <object, IConnectionFactory>(
                SiloConnectionFactory.ServicesKey,
                (sp, key) => ActivatorUtilities.CreateInstance <SocketConnectionFactory>(sp));
            services.AddSingletonKeyedService <object, IConnectionListenerFactory>(
                SiloConnectionListener.ServicesKey,
                (sp, key) => ActivatorUtilities.CreateInstance <SocketConnectionListenerFactory>(sp));
            services.AddSingletonKeyedService <object, IConnectionListenerFactory>(
                GatewayConnectionListener.ServicesKey,
                (sp, key) => ActivatorUtilities.CreateInstance <SocketConnectionListenerFactory>(sp));

            services.TryAddTransient <IMessageSerializer>(sp => ActivatorUtilities.CreateInstance <MessageSerializer>(sp,
                                                                                                                      sp.GetRequiredService <IOptions <SiloMessagingOptions> >().Value.MaxMessageHeaderSize,
                                                                                                                      sp.GetRequiredService <IOptions <SiloMessagingOptions> >().Value.MaxMessageBodySize));
            services.TryAddSingleton <ConnectionFactory, SiloConnectionFactory>();
            services.AddSingleton <NetworkingTrace>();
            services.AddSingleton <RuntimeMessagingTrace>();
            services.AddFromExisting <MessagingTrace, RuntimeMessagingTrace>();

            // Use Orleans server.
            services.AddSingleton <ILifecycleParticipant <ISiloLifecycle>, SiloConnectionListener>();
            services.AddSingleton <ILifecycleParticipant <ISiloLifecycle>, GatewayConnectionListener>();
            services.AddSingleton <SocketSchedulers>();
            services.AddSingleton <SharedMemoryPool>();

            // Logging helpers
            services.AddSingleton <SiloLoggingHelper>();
            services.AddFromExisting <ILifecycleParticipant <ISiloLifecycle>, SiloLoggingHelper>();
            services.AddFromExisting <IGrainIdLoggingHelper, SiloLoggingHelper>();
            services.AddFromExisting <IInvokeMethodRequestLoggingHelper, SiloLoggingHelper>();
        }
示例#28
0
        public void AddLocal <T>(Type type)
        {
            var instance = ActivatorUtilities.CreateInstance(_local, typeof(T));

            _local.AddService(typeof(T), instance);
        }
示例#29
0
        public async Task HandleMessage(IMessage message)
        {
            if (message.Source != MessageSource.User)
            {
                //Ignore all messages that are not from users
                return;
            }

            try
            {
                if (message.Content.StartsWith("!") && message.Content.Length > 1)
                {
                    _logger.Info("Processing message {0} from \"{1}\" in \"{2}\": \"{3}\"", message.Id, message.Author?.Username, message.Channel.Name, message.Content);

                    string[] msg = message.Content.Substring(1).Split(' ');

                    if (_commands.TryGetCommandType(msg[0], out Type iCommandType))
                    {
                        if (_filterChecker.ExecutionAllowed(iCommandType, message, _serviceProvider, out FilterScope? denyScope))
                        {
                            ICommand command = (ICommand)ActivatorUtilities.CreateInstance(_serviceProvider, iCommandType);

                            ArgumentsMapper mapper = new ArgumentsMapper(msg.Skip(1).ToArray(), command);
                            try
                            {
                                command = mapper.MapToInstance();
                            }
                            catch (CommandArgumentException cmdex)
                            {
                                await message.Channel.SendMessageAsync($":warning: {message.Author.Mention}, {cmdex.Message}. Type \"!help {msg[0]}\" for help");

                                return;
                            }

                            _logger.Debug("Message {0} from {1} is handled by {2}", message.Id, message.Author?.Username, iCommandType.FullName);
                            try
                            {
                                await command.Execute(message);
                            }
                            catch (Exception e)
                            {
                                _logger.Error(e, "Error in command execution for {0}. Message was: \"{1}\"", iCommandType.FullName, message.Content);
                                await ReportCommandHandelingError(message);
                            }
                        }
                        else
                        {
                            if (denyScope != FilterScope.Global)
                            {
                                _logger.Info("Execution of command \"{0}\" from {1} in channel {2} is not allowed", message.Content, message.Author?.Username, message.Channel?.Name);
                                await message.Channel.SendMessageAsync("What you are planning to do is not allowed here! :astonished::point_up:");
                            }
                        }
                    }
                    else
                    {
                        _logger.Info("Found no command handler for {0} in container", msg[0]);
                        if (message.IsPrivateMessage())
                        {
                            await message.Channel.SendMessageAsync("I don´t know what to do with this command :thinking:. What I do know, is that you can find help with the !help command! Isn´t that cool? :ok_hand:");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "Error in HandleMessage() for message {0} with content: \"{1}\"", message.Id, message.Content);
                await ReportCommandHandelingError(message);
            }
        }
示例#30
0
 public WorkflowStorageService(IEnumerable <IWorkflowStorageProvider> providers, ElsaOptions elsaOptions, IServiceProvider serviceProvider)
 {
     _defaultStorageProvider = (IWorkflowStorageProvider?)ActivatorUtilities.GetServiceOrCreateInstance(serviceProvider, elsaOptions.DefaultWorkflowStorageProviderType) !;
     _providersLookup        = providers.ToDictionary(x => x.Name);
 }