示例#1
0
 public IBatchCoordinatorKernel <T> Initialize(EnvironmentDefinition environment)
 {
     Environment = environment;
     Repository.SetEnvironment(environment.Name);
     Logger = Resolver.Activate <IBatchProgressLogger>().SetEnvironment(Environment);
     return(this);
 }
示例#2
0
        protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
        {
            var serviceHost = new ServiceHost(serviceType, baseAddresses);

            serviceHost.Description.Behaviors.Add(Resolver.Activate <IServiceBehavior>("IOC"));
            var configurator = Resolver.Activate <IServiceConfiguration>();

            configurator.ConfigureServiceHost(serviceHost, serviceType);
            SetBehaviour(serviceHost);
            if (!Interstellar.Utilities.Utilities.IsTestEnv() && !Interstellar.Utilities.Utilities.IsDevelopementEnv())
            {
                return(serviceHost);
            }
            var smb = serviceHost.Description.Behaviors.Find <ServiceMetadataBehavior>();

            if (smb == null)
            {
                smb = new ServiceMetadataBehavior();
                serviceHost.Description.Behaviors.Add(smb);
            }
            smb.HttpGetEnabled  = true;
            smb.HttpsGetEnabled = true;
            //serviceHost.Description.Behaviors.Add(new ServiceSecurityAuditBehavior{AuditLogLocation = AuditLogLocation.Application});
            serviceHost.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName, MetadataExchangeBindings.CreateMexHttpBinding(), "mex");
            serviceHost.Description.Behaviors.Add(new ErrorServiceBehavior());
            serviceHost.Faulted += serviceHost_Faulted;
            return(serviceHost);
        }
示例#3
0
        private static string GetServiceName(HttpApplication context)
        {
            var url = context.Request.Url.ToString();
            var i   = url.IndexOf(Securerest);

            url  = url.Remove(i);
            url += Securerest;
            var    urlFormater = Resolver.Activate <IUrlFormater>();
            string serviceName = null;

            if (serviceNameCache.TryGetValue(url, out serviceName))
            {
                return(serviceName);
            }
            foreach (var service in RuntimeFactory.Current.Context.GetRawConfigData <ConfigurationSet>().Endpoints)
            {
                if (service.Endpoints.Any(endpoint => url.Contains(endpoint.Address)))
                {
                    serviceName = service.ServiceName;
                }
                if (serviceName.ContainsCharacters())
                {
                    break;
                }
            }
            serviceNameCache.TryAdd(url, serviceName);
            return(serviceName);
        }
示例#4
0
        private static ChannelFactory <TService> CreateInstance <TService>(IRuntimeContext context, string servicename, string uri, bool isSecureRest) where TService : class
        {
            var builder = Resolver.Activate <IProxyBindingBuilder>().SetRuntimeContext(context);

            var channelFactory = Create <TService>(servicename, uri, builder);

            if (behaviorHandler != null)
            {
                behaviorHandler(channelFactory);
            }
            if (isSecureRest)
            {
                channelFactory.Endpoint.Behaviors.Add(new RestTokenHandler(servicename));
            }
            // if (!(channelFactory.Endpoint.Binding is WebHttpBinding))
            {
                foreach (OperationDescription op in channelFactory.Endpoint.Contract.Operations)
                {
                    var dataContractBehavior = op.Behaviors.Find <DataContractSerializerOperationBehavior>();
                    if (dataContractBehavior != null)
                    {
                        dataContractBehavior.MaxItemsInObjectGraph = int.MaxValue;
                    }
                }
            }
            if (channelFactory.Endpoint.Binding is WebHttpBinding)
            {
                Resolver.Activate <WebBehaviorProvider>().ApplyBehavior(channelFactory.Endpoint);
            }
            return(channelFactory);
        }
        private static ConfigurationSet GetConfigurationFromString(string payload)
        {
            var parser = Resolver.Activate <IReplaceableSerializer>();

            //Logging.DebugMessage(string.Format("Parser '{0}' loaded", parser.GetType().FullName));
            return(parser.GetConfigurationFromString(payload));
        }
示例#6
0
        public void CreateInstanceWithoutGenericParameterFunc()
        {
            Resolver.GetConfigurator().Bind <IDictionary <string, int> >().To <Dictionary <string, int> >();
            var actual = Resolver.Activate <IDictionary <string, int> >();

            Assert.IsInstanceOfType(actual, typeof(IDictionary <string, int>));
        }
示例#7
0
        public void CloneConfigSetWithServiceTest()
        {
            CleanUp();
            using (var csController = Resolver.Activate <IConfigSetTask>())
            {
                var envTask = Resolver.Activate <IEnvironmentTasks>();
                csController.CreateConfigSet(configSetName1, SystemName, null);
                var cs          = csController.GetConfigSet(configSetName1, SystemName);
                var environment = envTask.CreatEnvironment(cs, "Dev");
                var service     = csController.CreateService(cs, "ServiceName");
                var enpoint     = csController.CreateEndpoint(service, "EndpointName");

                Assert.Equal(configSetName1, cs.Name);
                Assert.Equal(SystemName, cs.System);
                Assert.Equal("ServiceName", service.Name);
                Assert.Equal(cs.Id, service.ConfigSetNameId);
                Assert.True(service.Id.Contains(cs.Id));
                Assert.Equal(27, enpoint.Parameters.Count());
                Assert.Equal(20, environment.SubstitutionParameters.Count);
                cs = csController.GetConfigSet(configSetName1, SystemName);


                csController.CreateConfigSet(configSetName2, SystemName, cs);
                var child = csController.GetConfigSet(configSetName2, SystemName);
                Assert.Equal(configSetName2, child.Name);
                Assert.Equal(SystemName, child.System);
                Assert.Equal(1, child.Services.Count);
                Assert.Equal(27, child.Services.First().Endpoints.First().Parameters.Count);
                Assert.Equal(20, child.Environments.First().SubstitutionParameters.Count);
                //return;
            }
        }
 /// <summary>
 /// This is called by WebActivator in web applications and must be
 /// called manually when used in other application types. This method initializes
 /// the framework. If you only use the IoC container and not the entire
 /// SOA framework add stardust.OnlyIoC= true to web.config ->
 /// appSettings in order to load only the needed components. If you use
 /// the SOA framework inherit from
 /// <see cref="CoreFrameworkBlueprint" /> to apply your own
 /// bindings as well as binding the framework it self. Load the binding
 /// configurations by calling Resolver.LoadModuleConfiguration()
 /// </summary>
 public static void InitializeModules()
 {
     try
     {
         var c = ConfigurationHelper.Configurations.Value;
         if (c != null && c.BindingConfigurationType != null)
         {
             Resolver.LoadModuleConfiguration();
             var appInitializer = Resolver.Activate <IStardustWebInitializer>();
             if (appInitializer.IsInstance())
             {
                 DynamicModuleUtility.RegisterModule(typeof(StardustWebInitializer));
             }
         }
     }
     catch
     {
     }
     if (ConfigurationManagerHelper.GetValueOnKey("stardust.OnlyIoC") == "true")
     {
         Resolver.LoadModuleConfiguration <CoreFrameworkBlueprint>();
     }
     else
     {
         new WebServerConfiguration().PrepWebServer(null);
     }
 }
        public void CreateLoggerTest()
        {
            RuntimeHelper.GetBinFolderLocation();
            var logger = Resolver.Activate <ILogging>();

            Assert.IsInstanceOfType(logger, typeof(ILogging));
        }
示例#10
0
 /// <summary>
 /// If Scope.PerRequest is specified the instance is created in an extended Context scope. that is, if it has not been used before in the scope a new will be created each time.
 /// </summary>
 /// <param name="scope"></param>
 /// <returns></returns>
 public static IRuntime CreateRuntime(Scope scope)
 {
     if (scope == Scope.Context)
     {
         return(CreateRuntime());
     }
     return(Resolver.Activate <IRuntime>(scope));
 }
示例#11
0
        internal static TOutItem Map <TInn, TOutItem>(TInn source, IMapContainer map, TOutItem target = default(TOutItem))
        {
            var rule = map.GetRule <TInn, TOutItem>();

            return((TOutItem)Resolver.Activate <ITypeConverter>(rule.BasicType)
                   .Initialize(rule)
                   .Convert(source, target));
        }
示例#12
0
        public static Binding CreateBinding(Endpoint serviceInterface)
        {
            var binding = Resolver.Activate <IBindingCreator>(BindingName(serviceInterface)).Create(serviceInterface);

            AddTimeoutSettings(binding, serviceInterface);

            return(binding);
        }
        public IServiceInitializer <T> Initialize(IRuntime runtime, string serviceName)
        {
            Runtime = runtime;
            var builder = Resolver.Activate <IProxyBindingBuilder>().SetRuntimeContext(runtime.Context);

            Proxy = (T)ObjectFactory.Createinstance(typeof(T), GetBindingParameters(serviceName, builder));
            return(this);
        }
示例#14
0
 internal static object Convert(KeyValuePair <string, IMapRules> mapRulese, object innPropValue, object target = null)
 {
     if (mapRulese.Value.Converter == null)
     {
         mapRulese.Value.Converter = Resolver.Activate <ITypeConverter>(mapRulese.Value.BasicType)
                                     .Initialize(mapRulese.Value);
     }
     return(mapRulese.Value.Converter.Convert(innPropValue, target));
 }
示例#15
0
        public void RestModuleConfiguration_GetDefault()
        {
            Resolver.RemoveAll();
            Resolver.LoadModuleConfiguration(new ConfigurationSettings());
            var expected = typeof(ModuleConfigTest);
            var actual   = Resolver.Activate <IModuleConfigTest>();

            Assert.AreEqual(expected, actual.GetType());
        }
示例#16
0
 public TokenManager()
 {
     if (HaveCheckedTokenManager)
     {
         return;
     }
     AlternateManagerCache   = Resolver.Activate <ITokenManagerCache>();
     HaveCheckedTokenManager = true;
 }
示例#17
0
 public static void ResetLogger <T>(Action <ILogging> initializationHandler = null) where T : ILogging
 {
     Resolver.GetConfigurator().UnBind <ILogging>().AllAndBind().To <T>();
     Logger1 = Resolver.Activate(initializationHandler);
     if (ModuleCreatorLoggerSet)
     {
         InitializeModuleCreatorWithDefalutLogger();
     }
 }
示例#18
0
        public void CreateNewInstanceIthConstructorParameters()
        {
            Resolver.GetConfigurator().Bind <IConstructorAttributeTest>().To <ConstructorAttributeTest>();
            Resolver.GetConfigurator().Bind <IConstructorParameterTest>().To <ConstructorParameterTest>();
            var item = Resolver.Activate <IConstructorParameterTest>();

            Assert.IsNotNull(item);
            Assert.IsNotNull(item.MyConstructorAttribute);
        }
示例#19
0
        public void ResolveFromConfigSection()
        {
            var defaultInstance   = Resolver.Activate <IConfiguredInstance>();
            var defaultInstance2  = Resolver.Activate <IConfiguredInstance>();
            var alternateInstance = Resolver.Activate <IConfiguredInstance>("fromConfig");

            Assert.IsInstanceOfType(defaultInstance, typeof(DefaultInstance));
            Assert.AreSame(defaultInstance, defaultInstance2);
            Assert.IsInstanceOfType(alternateInstance, typeof(AlternateInstance));
        }
示例#20
0
        /// <summary>
        /// Creates a new instance of <see cref="IComponentRegistration"/>.
        /// Use this if you need more than one instance of the interface that stores files in separate locations.
        /// The instance is initialized if you pass a value in path.
        /// </summary>
        public static IComponentRegistration CreateNewComponentRegistration(string path)
        {
            var item = Resolver.Activate <IComponentRegistration>();

            if (path.IsNullOrWhiteSpace())
            {
                return(item);
            }
            return(item.SetFolder(path).Enumerate());
        }
示例#21
0
        public bool PushChange(string id, string environment)
        {
            var env = GetEnvironment(id, environment);

            env.ETag        = DateTimeOffset.UtcNow.Ticks.ToString();
            env.LastPublish = DateTime.UtcNow;
            UpdateEnvironment(env);
            var cacheService = Resolver.Activate <ICacheManagementService>();

            return(cacheService != null && cacheService.TryUpdateCache(id, environment));
        }
示例#22
0
 public T GetClient()
 {
     if (client.IsNull())
     {
         url = string.Format("{0}{1}", endpoint.PropertyBag["Address"], endpoint.PropertyBag["ListenerKey"]);
         var queueClient = QueueClient.CreateFromConnectionString(url, String.Format(endpoint.PropertyBag["QueueName"], ConfigurationManagerHelper.GetValueOnKey("dataCenterName")));
         client = Resolver.Activate <IQueueClient>(ServiceName);
         client.Initialize(queueClient);
     }
     return((T)client);
 }
示例#23
0
        /// <summary>
        /// Enables inspection or modification of a message after a reply message is received but prior to passing it back to the client application.
        /// </summary>
        /// <param name="reply">The message to be transformed into types and handed back to the client application.</param><param name="correlationState">Correlation state data.</param>
        public void AfterReceiveReply(ref Message reply, object correlationState)
        {
            try
            {
                var runtime = correlationState as IRuntime;
                if (runtime == null)
                {
                    return;
                }
                HttpResponseMessageProperty httpRequest;
                if (reply.Properties.ContainsKey(HttpResponseMessageProperty.Name))
                {
                    httpRequest = reply.Properties[HttpResponseMessageProperty.Name] as HttpResponseMessageProperty;
                    var msg = httpRequest.Headers["X-Stardust-Meta"];
                    if (msg.ContainsCharacters())
                    {
                        try
                        {
                            var item = Resolver.Activate <IReplaceableSerializer>().Deserialize <ResponseHeader>(Convert.FromBase64String(msg).GetStringFromArray());
                            if (runtime.CallStack == null)
                            {
                                return;
                            }
                            if (runtime.CallStack.CallStack != null)
                            {
                                runtime.CallStack.CallStack.Add(item.CallStack);
                            }
                        }
                        catch
                        {
                            // ignored
                        }
                    }
                    //if ((int)httpRequest.StatusCode < 200 || (int)httpRequest.StatusCode > 204)
                    //{
                    //    try
                    //    {
                    //        var errorMsg = reply.GetBody<ErrorMessage>(new DataContractJsonSerializer(typeof(ErrorMessage)));
                    //        throw new FaultException<ErrorMessage>(errorMsg);
                    //    }
                    //    catch (Exception ex)
                    //    {

                    //        throw new StardustCoreException("Unable to grab error body....",ex);
                    //    }
                    //}
                }
            }
            catch (Exception ex)
            {
                ex.Log();
            }
        }
示例#24
0
        public void CreateDuplicateSet()
        {
            CleanUp();
            using (var csController = Resolver.Activate <IConfigSetTask>())
            {
                csController.CreateConfigSet(configSetName1, SystemName, null);
                var cs = csController.GetConfigSet(configSetName1, SystemName);

                Assert.Throws <AmbiguousMatchException>(
                    () => csController.CreateConfigSet(configSetName1, SystemName, null));
            }
        }
示例#25
0
        public T GetClient()
        {
            if (Sender.IsInstance())
            {
                return(Sender);
            }
            var notificationHub = EventHubClient.CreateFromConnectionString(ServiceRoot, GetEndpointSettings(ServiceName).PropertyBag["PublisherName"]);
            var sender          = notificationHub.CreateSender(GetEndpointSettings(ServiceName).PropertyBag["PublisherName"]);

            Sender = (T)Resolver.Activate <INotificationService>(ServiceName, s => s.Initialize(sender));
            return(Sender);
        }
示例#26
0
 private static void SetUpStardust()
 {
     Resolver.LoadModuleConfiguration <Blueprint>();
     Resolver.GetConfigurator().Bind <ITestClass>().To <TestClass>().SetSingletonScope();
     Resolver.GetConfigurator().Bind <ITestClass>().ToConstructor(() => new TestClass(), ServiceName).SetSingletonScope();
     Resolver.GetConfigurator().Bind <ITestClass2>().To <TestClass2>().SetTransientScope();
     Resolver.GetConfigurator().Bind <ITestClass3>().To <TestClass3>().SetTransientScope();
     Resolver.Activate <ITestClass>();
     Resolver.Activate <ITestClass2>();
     Resolver.Activate <ITestClass3>();
     ContainerFactory.Current.KillAllInstances();
 }
示例#27
0
        public void TestResolver()
        {
            Resolver.GetConfigurator().Bind <ITestInterface <long> >().To <TestInterface <long> >().SetRequestResponseScope();
            Resolver.GetConfigurator().Bind <string>().To <string>().SetRequestResponseScope();
            Resolver.GetConfigurator().Bind <Int32>().To <Int32>().SetRequestResponseScope();
            ContainerFactory.Current.Bind(typeof(string), "test", Scope.Context);
            ContainerFactory.Current.Bind(typeof(Int32), 10, Scope.Context);
            var actual   = Resolver.Activate <ITestInterface <long> >() as TestInterface <long>;
            var expected = new TestInterface <long>("test", 10);

            Assert.AreEqual(expected.Test, actual.Test);
            Assert.AreEqual(expected.Test2, actual.Test2);
        }
示例#28
0
 public ISetupContext BindItAll()
 {
     Resolver.GetConfigurator().Bind <IControllerFactory>().To <StardustControllerFactory>().SetSingletonScope();
     Resolver.GetConfigurator().Bind <IControllerActivator>().To <StardustControllerActivator>().SetSingletonScope().DisableOverride();
     Resolver.GetConfigurator().Bind <IHttpActionInvoker>().To <ApiTeardownActionFilter>().SetSingletonScope();
     Resolver.GetConfigurator().Bind <IAsyncActionInvoker>().To <ControllerTearDownActionFilter>().SetSingletonScope();
     Resolver.GetConfigurator().Bind <IActionInvoker>().To <ControllerTearDownActionFilter>().SetSingletonScope();
     Resolver.GetConfigurator().Bind <IHttpControllerActivator>().To <StardustApiControllerActivator>().SetSingletonScope();
     //Resolver.GetConfigurator().Bind<System.Web.Http.Metadata.ModelMetadataProvider>().ToAssembly(typeof(System.Web.Http.Metadata.ModelMetadataProvider).Assembly);
     GlobalConfiguration.Configuration.DependencyResolver = new StardustDependencyResolver();
     ControllerBuilder.Current.SetControllerFactory(Resolver.Activate <IControllerFactory>());
     return(new SetupContext(Application));
 }
示例#29
0
 private static void SetBehaviour(ServiceHost serviceHost)
 {
     try
     {
         var behaviourSetup = Resolver.Activate <IServiceHostBehaviour>();
         behaviourSetup.ConfigureBehaviours(serviceHost);
         behaviourSetup.SetThrottling(serviceHost);
     }
     catch (Exception ex)
     {
         Logging.Exception(ex, "Failed to set behaviours");
     }
 }
示例#30
0
 public static EndpointAddress EndpointAddress(string serviceName, Endpoint serviceInterface,string rootUrl)
 {
     try
     {
         var formater = Resolver.Activate<IEndpointUrlFormater>();
         return formater.GetEndpointAddress(serviceName, serviceInterface, rootUrl);
     }
     catch (Exception ex)
     {
         
         throw new FormatException("Failure formating endpoint address",ex);
     }
 }