Exemplo n.º 1
0
        /// <summary>
        /// Registers a given instance for a given service type and a given name.
        /// </summary>
        /// <typeparam name="TInterface">The type that is being registered.</typeparam>
        /// <param name="factory">The factory method able to create the instance that
        /// must be returned when the given type is resolved.</param>
        /// <param name="name">The name for which the given instance is registered.</param>
        public void Register <TInterface>(Func <TInterface> factory, string name) where TInterface : class
        {
            if (factory == null)
            {
                throw new ArgumentNullException(nameof(factory));
            }
            var serviceType = typeof(TInterface);
            var key         = new InstanceKey(serviceType, name);

            if (_factories.ContainsKey(key))
            {
                throw new ServiceAlreadyRegisteredException(serviceType, null);
            }

            _factories.Add(key, factory);
            if (name == null)
            {
                return;
            }

            if (!_namedInstances.TryGetValue(serviceType, out List <string> instances))
            {
                instances = new List <string>();
                _namedInstances.Add(serviceType, instances);
            }
            instances.Add(name);
        }
Exemplo n.º 2
0
        protected override int CountInstancesInternal(InstanceKey classInstanceKey)
        {
            InstanceHandle ihClass = GetInstance(classInstanceKey);

            InstanceHandle[] insts = GetRelatedInstances(GetInstance(classInstanceKey), GetInstance(KnownRelationshipGuids.Class__has__Instance));
            return(insts.Length);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Factory method you should use instead of the constructor for this class.
        /// This will construct a new instance if and only if there isn't already
        /// an instance made for this particular kOSProcessor, for the given body
        /// (Uniqueness determinied by the Body's text name.  If someone makes
        /// a modded solar system with two bodies having the same name, that
        /// will be a problem (but who would do that??) ).
        /// If an instance already exists it will return a reference to that instead of making
        /// a new one.
        /// The reason this enforcement is needed is because BodyTarget has callback hooks
        /// that prevent orphaning and garbage collection.  (The delegate inserted
        /// into KSP's GameEvents counts as a reference to the BodyTarget.)
        /// Using this factory method instead of a constructor prevents having multiple
        /// instances of BodyTarget.
        /// </summary>
        /// <returns>The or get.</returns>
        /// <param name="body">celestial body to make the wrapper for</param>
        /// <param name="Shared">kOS shared objects reference</param>
        public static BodyTarget CreateOrGetExisting(CelestialBody body, SharedObjects shared)
        {
            if (instanceCache == null)
            {
                instanceCache = new Dictionary <InstanceKey, WeakReference>();
            }

            InstanceKey key = new InstanceKey {
                ProcessorId = shared.Processor.KOSCoreId, BodyName = body.name
            };

            if (instanceCache.ContainsKey(key))
            {
                WeakReference weakRef = instanceCache[key];
                if (weakRef.IsAlive)
                {
                    return((BodyTarget)weakRef.Target);
                }
                else
                {
                    instanceCache.Remove(key);
                }
            }
            // If it either wasn't in the cache, or it was but the GC destroyed it by now, make a new one:
            BodyTarget newlyConstructed = new BodyTarget(body, shared);

            instanceCache.Add(key, new WeakReference(newlyConstructed));
            return(newlyConstructed);
        }
Exemplo n.º 4
0
 public BaseFormParent()
 {
     InitializeComponent();
     this.Key = InstanceKey.Generate(this);
     RegisterForm();
     PerformAction();
 }
Exemplo n.º 5
0
        /// <summary>
        /// This method resolves a service object request
        /// </summary>
        /// <param name="serviceType">Service object type</param>
        /// <param name="name">Service instance name</param>
        /// <returns>Service instance, if found; otherwise, null</returns>
        private object ObtainService(Type serviceType, string name = null)
        {
            var key = new InstanceKey(serviceType, name);

            return(_factories.TryGetValue(key, out Func <object> factory)
                ? factory()
                : null);
        }
Exemplo n.º 6
0
 protected override InstanceHandle GetInstanceInternal(InstanceKey key)
 {
     if (GetDefaultTenant()._instsByKey.ContainsKey(key))
     {
         return(GetDefaultTenant()._instsByKey[key]);
     }
     return(InstanceHandle.Empty);
 }
            public LoadOrCreateAsyncResult(PersistenceProviderDirectory ppd, InstanceKey key, Guid suggestedIdOrId, bool canCreateInstance, ICollection <InstanceKey> associatedKeys, Transaction transaction, bool loadAny, TimeSpan timeout, AsyncCallback callback, object state) : base(callback, state)
            {
                bool flag;

                this.ppd               = ppd;
                this.key               = key;
                this.suggestedIdOrId   = suggestedIdOrId;
                this.canCreateInstance = canCreateInstance;
                this.associatedKeys    = associatedKeys;
                this.transaction       = transaction;
                this.loadAny           = loadAny;
                this.timeoutHelper     = new TimeoutHelper(timeout);
                if ((this.associatedKeys != null) && (this.associatedKeys.Count == 0))
                {
                    this.associatedKeys = null;
                }
                base.OnCompleting = onComplete;
                if (this.transaction != null)
                {
                    TransactionInterop.GetDtcTransaction(this.transaction);
                }
                Exception exception = null;

                try
                {
                    this.result = this.loadAny ? null : this.ppd.LoadFromCache(this.key, this.suggestedIdOrId, this.canCreateInstance);
                    if (this.result != null)
                    {
                        flag = true;
                    }
                    else
                    {
                        if ((this.ppd.store == null) && !this.canCreateInstance)
                        {
                            if (this.key != null)
                            {
                                throw System.ServiceModel.Activities.FxTrace.Exception.AsError(new InstanceKeyNotReadyException(null, this.key));
                            }
                            throw System.ServiceModel.Activities.FxTrace.Exception.AsError(new InstanceNotReadyException(null, this.suggestedIdOrId));
                        }
                        IAsyncResult result = this.ppd.BeginReserveThrottle(this.timeoutHelper.RemainingTime(), base.PrepareAsyncCompletion(handleReserveThrottle), this);
                        flag = base.SyncContinue(result);
                    }
                }
                catch (Exception exception2)
                {
                    if (Fx.IsFatal(exception2))
                    {
                        throw;
                    }
                    exception = exception2;
                    flag      = true;
                }
                if (flag)
                {
                    base.Complete(true, exception);
                }
            }
Exemplo n.º 8
0
            /// <summary>
            /// Computes a key for storing and identifying an instance in the cache.
            /// </summary>
            /// <param name="type">Type of instance to get</param>
            /// <param name="properties">List of properties and values</param>
            /// <param name="parentInstance">Parent instance. Can be NULL if this is the root instance.</param>
            /// <returns>
            /// InstanceKey that will be unique for given set of identifiers values for the type. If the type isn't associated with any
            /// identifier, the return value is made unique by generating a Guid.
            /// ASSUMES GetIdentifiers(type) ALWAYS RETURN IDENTIFIERS IN THE SAME ORDER FOR A GIVEN TYPE.
            /// This is certainly the case as long as GetIdentifiers caches its result for a given type (which it does by 2016-11-25).
            /// </returns>
            private static InstanceKey GetCacheKey(Type type, IDictionary <string, object> properties, object parentInstance)
            {
                var identifierValues = GetIdentifiers(type)?.Select(id => properties[id]).DefaultIfEmpty(Guid.NewGuid()).ToArray()
                                       ?? new object[] { Guid.NewGuid() };

                var key = new InstanceKey(type, identifierValues, parentInstance);

                return(key);
            }
 private InstancePersistenceCommand CreateLoadCommandHelper(InstanceKey key, out InstanceHandle handle, bool canCreateInstance, Guid suggestedIdOrId, ICollection <InstanceKey> associatedKeys, bool loadAny)
 {
     if (loadAny)
     {
         handle = this.store.CreateInstanceHandle(this.owner);
         return(new TryLoadRunnableWorkflowCommand());
     }
     if (key != null)
     {
         LoadWorkflowByInstanceKeyCommand command;
         handle = this.store.CreateInstanceHandle(this.owner);
         if (canCreateInstance)
         {
             command = new LoadWorkflowByInstanceKeyCommand {
                 LookupInstanceKey = key.Value,
                 AssociateInstanceKeyToInstanceId = (suggestedIdOrId == Guid.Empty) ? Guid.NewGuid() : suggestedIdOrId,
                 AcceptUninitializedInstance      = true
             };
         }
         else
         {
             command = new LoadWorkflowByInstanceKeyCommand {
                 LookupInstanceKey = key.Value
             };
         }
         InstanceKey keyToAdd = ((canCreateInstance && (key.Metadata != null)) && (key.Metadata.Count > 0)) ? key : null;
         if (associatedKeys != null)
         {
             foreach (InstanceKey key3 in associatedKeys)
             {
                 if (key3 == key)
                 {
                     if (!canCreateInstance)
                     {
                         continue;
                     }
                     keyToAdd = null;
                 }
                 TryAddKeyToInstanceKeysCollection(command.InstanceKeysToAssociate, key3);
             }
         }
         if (keyToAdd != null)
         {
             TryAddKeyToInstanceKeysCollection(command.InstanceKeysToAssociate, keyToAdd);
         }
         return(command);
     }
     if (associatedKeys != null)
     {
         throw System.ServiceModel.Activities.FxTrace.Exception.AsError(new InvalidOperationException(System.ServiceModel.Activities.SR.NoAdditionalKeysOnInstanceIdLoad));
     }
     handle = this.store.CreateInstanceHandle(this.owner, (suggestedIdOrId == Guid.Empty) ? Guid.NewGuid() : suggestedIdOrId);
     return(new LoadWorkflowCommand {
         AcceptUninitializedInstance = canCreateInstance
     });
 }
Exemplo n.º 10
0
        public bool CalculateKeys(Message message, out InstanceKey instanceKey, out ICollection <InstanceKey> additionalKeys)
        {
            MessageCalculator messageCalculator = this.messageCalculator;

            if (messageCalculator == null)
            {
                messageCalculator = this.messageCalculator = new MessageCalculator(this);
            }
            return(messageCalculator.CalculateKeys(message, null, out instanceKey, out additionalKeys));
        }
            void TraceCorrelationKeys(InstanceKey instanceKey, Dictionary <string, string> values)
            {
                StringBuilder keyValueAsString = new StringBuilder();

                foreach (KeyValuePair <string, string> pair in values)
                {
                    keyValueAsString.Append(pair.Key).Append(":").Append(pair.Value).Append(',');
                }
                TD.TraceCorrelationKeys(instanceKey.Value, keyValueAsString.ToString(), this.parent.scopeName.ToString());
            }
Exemplo n.º 12
0
        public CorrelationMessageProperty(InstanceKey correlationKey, IEnumerable <InstanceKey> additionalKeys, IEnumerable <InstanceKey> transientCorrelations)
        {
            if (correlationKey == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("correlationKey");
            }

            if (additionalKeys == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("additionalKeys");
            }

            this.correlationKey = correlationKey;

            ICollection <InstanceKey> additionalKeysCollection = additionalKeys as ICollection <InstanceKey>;

            if (additionalKeysCollection != null && additionalKeysCollection.Count == 0)
            {
                this.additionalKeys = emptyInstanceKeyList;
            }
            else
            {
                this.additionalKeys = additionalKeys as ReadOnlyCollection <InstanceKey>;
                if (this.additionalKeys == null)
                {
                    IList <InstanceKey> additionalKeysList = additionalKeys as IList <InstanceKey>;
                    if (additionalKeysList == null)
                    {
                        additionalKeysList = new List <InstanceKey>(additionalKeys);
                    }
                    this.additionalKeys = new ReadOnlyCollection <InstanceKey>(additionalKeysList);
                }
            }

            ICollection <InstanceKey> transientCorrelationsCollection = transientCorrelations as ICollection <InstanceKey>;

            if (transientCorrelations == null || (transientCorrelationsCollection != null && transientCorrelationsCollection.Count == 0))
            {
                this.transientCorrelations = emptyInstanceKeyList;
            }
            else
            {
                this.transientCorrelations = transientCorrelations as ReadOnlyCollection <InstanceKey>;
                if (this.transientCorrelations == null)
                {
                    IList <InstanceKey> transientCorrelationsList = transientCorrelations as IList <InstanceKey>;
                    if (transientCorrelationsList == null)
                    {
                        transientCorrelationsList = new List <InstanceKey>(transientCorrelations);
                    }
                    this.transientCorrelations = new ReadOnlyCollection <InstanceKey>(transientCorrelationsList);
                }
            }
        }
Exemplo n.º 13
0
            private void TraceCorrelationKeys(InstanceKey instanceKey, Dictionary <string, string> values)
            {
                StringBuilder builder = new StringBuilder();

                foreach (KeyValuePair <string, string> pair in values)
                {
                    StringBuilder introduced3 = builder.Append(pair.Key).Append(":");
                    introduced3.Append(pair.Value).Append(',');
                }
                TD.TraceCorrelationKeys(instanceKey.Value, builder.ToString(), this.parent.scopeName.ToString());
            }
 public SerializableInstanceKey(InstanceKey instanceKey)
 {
     this.value = instanceKey.Value;
     if (instanceKey.Metadata != null)
     {
         this.metadata = new Dictionary <XName, SerializableInstanceValue>(instanceKey.Metadata.Count);
         foreach (KeyValuePair <XName, InstanceValue> pair in instanceKey.Metadata)
         {
             this.metadata.Add(pair.Key, new SerializableInstanceValue(pair.Value));
         }
     }
 }
 public IAsyncResult BeginLoad(InstanceKey key, ICollection <InstanceKey> associatedKeys, Transaction transaction, TimeSpan timeout, AsyncCallback callback, object state)
 {
     if (key == null)
     {
         throw System.ServiceModel.Activities.FxTrace.Exception.ArgumentNull("key");
     }
     if (key.Value == Guid.Empty)
     {
         throw System.ServiceModel.Activities.FxTrace.Exception.Argument("key", System.ServiceModel.Activities.SR.InvalidKey);
     }
     return(new LoadOrCreateAsyncResult(this, key, Guid.Empty, false, associatedKeys, transaction, false, timeout, callback, state));
 }
Exemplo n.º 16
0
        public static void Main(string[] args)
        {
            Oms oms = new MemoryOms();

            oms.InitializeTenants("System/Tenants");

            oms.Load("System/Snapshots");

            oms.DefaultTenant = oms.GetTenant("archalos1");

            TestExisting(oms);
            oms.BeginTransaction();

            InstanceHandle ihInventoryItem = oms.CreateClass(LocalInstanceGuids.Classes.InventoryItem, "InventoryItem", "Inventory Item");
            InstanceHandle ihCharacter     = oms.CreateClass(LocalInstanceGuids.Classes.Character, "Character", "Character");
            InstanceHandle ihGender        = oms.CreateClass(LocalInstanceGuids.Classes.Character, "Gender", "Gender");

            oms.CommitTransaction();

            oms.BeginTransaction();

            InstanceHandle ikCharacter__has__Gender = oms.CreateRelationshipInstance(ihCharacter, "has", ihGender, LocalRelationshipGuids.Character__has__Gender);
            InstanceHandle ihGender1 = oms.CreateInstance(ihGender);

            oms.CommitTransaction();
            oms.BeginTransaction();

            InstanceHandle ikCharacter__Ashlyn = oms.CreateInstance(LocalInstanceGuids.Characters.Ashlyn, LocalInstanceGuids.Classes.Character);

            oms.CreateRelationship(ikCharacter__Ashlyn, ikCharacter__has__Gender, ihGender1);

            oms.CommitTransaction();

            InstanceHandle ihClass = oms.GetInstance(InstanceKey.Parse("1$1"));

            ihClass = oms.GetInstance(KnownInstanceGuids.Classes.Class);

            Guid id = Guid.Empty;


            bool verified = oms.Transactions.Verify();

            InstanceHandle ihGndr = oms.GetRelatedInstance(ikCharacter__Ashlyn, ikCharacter__has__Gender);

            // InstanceKey key = oms.GetInstanceKey(ihGndr);

            InstanceHandle ihGnd2 = oms.GetRelatedInstance(ikCharacter__Ashlyn, ikCharacter__has__Gender);

            oms.Save("System/Snapshots");

            Console.WriteLine(ikCharacter__Ashlyn.ToString());
        }
        public CorrelationMessageProperty(InstanceKey correlationKey, IEnumerable <InstanceKey> additionalKeys, IEnumerable <InstanceKey> transientCorrelations)
        {
            if (correlationKey == null)
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("correlationKey");
            }
            if (additionalKeys == null)
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("additionalKeys");
            }
            this.correlationKey = correlationKey;
            ICollection <InstanceKey> is2 = additionalKeys as ICollection <InstanceKey>;

            if ((is2 != null) && (is2.Count == 0))
            {
                this.additionalKeys = emptyInstanceKeyList;
            }
            else
            {
                this.additionalKeys = additionalKeys as ReadOnlyCollection <InstanceKey>;
                if (this.additionalKeys == null)
                {
                    IList <InstanceKey> list = additionalKeys as IList <InstanceKey>;
                    if (list == null)
                    {
                        list = new List <InstanceKey>(additionalKeys);
                    }
                    this.additionalKeys = new ReadOnlyCollection <InstanceKey>(list);
                }
            }
            ICollection <InstanceKey> is3 = transientCorrelations as ICollection <InstanceKey>;

            if ((transientCorrelations == null) || ((is3 != null) && (is3.Count == 0)))
            {
                this.transientCorrelations = emptyInstanceKeyList;
            }
            else
            {
                this.transientCorrelations = transientCorrelations as ReadOnlyCollection <InstanceKey>;
                if (this.transientCorrelations == null)
                {
                    IList <InstanceKey> list2 = transientCorrelations as IList <InstanceKey>;
                    if (list2 == null)
                    {
                        list2 = new List <InstanceKey>(transientCorrelations);
                    }
                    this.transientCorrelations = new ReadOnlyCollection <InstanceKey>(list2);
                }
            }
        }
        internal ReadOnlyCollection <BookmarkInfo> GetBookmarksForInstance(InstanceKey instanceKey)
        {
            ReadOnlyCollection <BookmarkInfo> bookmarks = null;

            lock (this.ThisLock)
            {
                PersistenceContext context;
                if (this.keyMap.TryGetValue(instanceKey.Value, out context))
                {
                    bookmarks = context.Bookmarks;
                }
            }
            return(bookmarks);
        }
        public RpcObjectRef <TService>?GetPublishedInstance <TService>(TService serviceInstance) where TService : class
        {
            var connectionInfo = this.RetrieveConnectionInfo();

            lock (this.syncRoot)
            {
                var key = new InstanceKey(serviceInstance);
                if (this.serviceImplToId.TryGetValue(key, out var objectId))
                {
                    return(new RpcObjectRef <TService>(connectionInfo, objectId, this.GetPublishedServices(objectId).ToArray()));
                }
            }

            return(null);
        }
        protected void GetInstanceKeys(OperationContext operationContext, out InstanceKey instanceKey, out ICollection <InstanceKey> additionalKeys)
        {
            CorrelationMessageProperty property = null;

            instanceKey    = InstanceKey.InvalidKey;
            additionalKeys = new ReadOnlyCollection <InstanceKey>(new InstanceKey[0]);
            if (!CorrelationMessageProperty.TryGet(operationContext.IncomingMessageProperties, out property))
            {
                if (this.keyCalculator != null)
                {
                    InstanceKey key;
                    ICollection <InstanceKey> is2;
                    MessageBuffer             buffer;
                    bool flag;
                    if (operationContext.IncomingMessageProperties.TryGetValue <MessageBuffer>("_RequestMessageBuffer_", out buffer))
                    {
                        flag = this.keyCalculator.CalculateKeys(buffer, operationContext.IncomingMessage, out key, out is2);
                    }
                    else
                    {
                        flag = this.keyCalculator.CalculateKeys(operationContext.IncomingMessage, out key, out is2);
                    }
                    if (flag)
                    {
                        if (key != null)
                        {
                            instanceKey = key;
                        }
                        if (is2 != null)
                        {
                            additionalKeys = is2;
                        }
                        property = new CorrelationMessageProperty(instanceKey, additionalKeys);
                        operationContext.IncomingMessageProperties.Add(CorrelationMessageProperty.Name, property);
                    }
                }
            }
            else
            {
                instanceKey    = property.CorrelationKey;
                additionalKeys = property.AdditionalKeys;
            }
            if (((instanceKey == null) || !instanceKey.IsValid) && !this.CanCreateInstance)
            {
                this.host.RaiseUnknownMessageReceived(operationContext.IncomingMessage);
                throw System.ServiceModel.Activities.FxTrace.Exception.AsError(new FaultException(new DurableDispatcherAddressingFault()));
            }
        }
Exemplo n.º 21
0
        public BaseFormParent InstanceOf <T>() where T : BaseFormParent
        {
            BaseFormParent result = null;
            var            type   = typeof(T);

            //if typeInstance dict contains form with specific type
            if (typeInstanceDict.ContainsKey(type))
            {
                //Get Instance Key by Type
                if (typeInstanceDict.TryGetValue(type, out var instanceKey))
                {
                    //Get Frm by InstanceKey
                    if (ActiveForms.ContainsKey(instanceKey))
                    {
                        result = ActiveForms[instanceKey];
                    }
                    else
                    {
                        throw new Exception("Форма отсутствует в списке активных форм, хотя тип и ключ формы зарегистрирован");
                    }
                }
                else
                {
                    throw new Exception("Ключ формы не зарегистрирован");
                }
            }
            //If typeInstance dict doesn't contains InstanceKey of Form with Specific Type
            //Create Element in typeInstance dict
            else
            {
                //Instance of Form
                var form        = (T)Activator.CreateInstance(type);
                var instanceKey = InstanceKey.Generate(form);
                typeInstanceDict.Add(type, instanceKey);

                if (ActiveForms.ContainsKey(instanceKey))
                {
                    ActiveForms[instanceKey] = form;
                }
                else
                {
                    ActiveForms.Add(instanceKey, form);
                }
                result = ActiveForms[instanceKey];
            }

            return(result);
        }
Exemplo n.º 22
0
        bool TryGetMessageVersion(InstanceKey instanceKey, out MessageVersion version)
        {
            Fx.Assert(instanceKey != null, "Expect a valid instanceKey here");
            version = MessageVersion.None;
            if (instanceKey != null)
            {
                InstanceValue messageVersionValue;
                if (instanceKey.Metadata.TryGetValue(WorkflowServiceNamespace.MessageVersionForReplies, out messageVersionValue))
                {
                    version = (MessageVersion)messageVersionValue.Value;
                    return(true);
                }
            }

            return(false);
        }
Exemplo n.º 23
0
        public ConstructorInstance ToInstance(IPluginFactory factory, Type pluginType)
        {
            var plugin = factory.PluginFor(PluggedType());

            var instance = new ConstructorInstance(plugin);

            if (InstanceKey.IsNotEmpty())
            {
                instance.Name = InstanceKey;
            }

            var reader = new InstanceMementoPropertyReader(instance, this, factory);

            plugin.VisitArguments(reader);

            return(instance);
        }
            public ControlOperationAsyncResult(ControlOperationInvoker invoker, object[] inputs, IInvokeReceivedNotification notification, TimeSpan timeout, AsyncCallback callback, object state) : base(callback, state)
            {
                this.instanceKey      = InstanceKey.InvalidKey;
                this.additionalKeys   = emptyKeyCollection;
                this.outputs          = ControlOperationInvoker.emptyObjectArray;
                this.invoker          = invoker;
                this.inputs           = inputs;
                this.timeoutHelper    = new TimeoutHelper(timeout);
                this.transaction      = Transaction.Current;
                this.operationContext = OperationContext.Current;
                base.OnCompleting     = onCompleting;
                bool flag  = false;
                bool flag2 = false;

                try
                {
                    if (notification != null)
                    {
                        if (this.operationContext.SessionId == null)
                        {
                            notification.NotifyInvokeReceived();
                        }
                        else
                        {
                            this.notification = notification;
                        }
                    }
                    if (invoker.BufferedReceiveManager != null)
                    {
                        ReceiveContext.TryGet(this.operationContext.IncomingMessageProperties, out this.receiveContext);
                    }
                    flag  = this.Process();
                    flag2 = true;
                }
                finally
                {
                    if (!flag2)
                    {
                        Finally(this, null);
                    }
                }
                if (flag)
                {
                    base.Complete(true);
                }
            }
        public Transaction GetTransactionForInstance(InstanceKey instanceKey)
        {
            Transaction lockingTransaction = null;

            lock (this.ThisLock)
            {
                PersistenceContext context;
                if (this.keyMap.TryGetValue(instanceKey.Value, out context))
                {
                    lockingTransaction = context.LockingTransaction;
                    if (lockingTransaction != null)
                    {
                        lockingTransaction = lockingTransaction.Clone();
                    }
                }
            }
            return(lockingTransaction);
        }
        private PersistenceContext LoadFromCache(InstanceKey key, Guid suggestedIdOrId, bool canCreateInstance)
        {
            PersistenceContext context = null;

            if ((key != null) || (suggestedIdOrId != Guid.Empty))
            {
                lock (this.ThisLock)
                {
                    this.ThrowIfClosedOrAborted();
                    if (key == null)
                    {
                        this.instanceCache.TryGetValue(suggestedIdOrId, out context);
                        return(context);
                    }
                    this.keyMap.TryGetValue(key.Value, out context);
                }
            }
            return(context);
        }
 internal void InitializeBookmarkScope(NativeActivityContext context, InstanceKey instanceKey)
 {
     if (this.Scope == null)
     {
         this.bookmarkScopeHandle.CreateBookmarkScope(context, instanceKey.Value);
         this.Scope = this.bookmarkScopeHandle.BookmarkScope;
     }
     else if (this.Scope.IsInitialized)
     {
         if (this.Scope.Id != instanceKey.Value)
         {
             throw System.ServiceModel.Activities.FxTrace.Exception.AsError(new InvalidOperationException(System.ServiceModel.Activities.SR.CorrelationHandleInUse(this.Scope.Id, instanceKey.Value)));
         }
     }
     else
     {
         this.Scope.Initialize(context, instanceKey.Value);
     }
 }
        public RpcObjectRef <TService> GetOrPublishInstance <TService>(TService serviceInstance) where TService : class
        {
            if (serviceInstance is null)
            {
                throw new ArgumentNullException(nameof(serviceInstance));
            }

            InstanceKey key;

            lock (this.syncRoot)
            {
                key = new InstanceKey(serviceInstance);
                if (this.serviceImplToId.TryGetValue(key, out var instanceId))
                {
                    return(new RpcObjectRef <TService>(this.connectionInfo, instanceId, this.GetPublishedServices(instanceId).ToArray()));
                }
            }

            // Not published, so we try to register the serviceInstance's service definitions
            // and then publish it.

            var allServices = RpcBuilderUtil.GetAllServices(serviceInstance.GetType(), true);

            this.TryRegisterServiceDefinitions(allServices, null);

            var connectionInfo = this.RetrieveConnectionInfo();

            lock (this.syncRoot)
            {
                // Let's try again.
                if (this.serviceImplToId.TryGetValue(key, out var instanceId))
                {
                    // Somebody beat us to it.
                    return(new RpcObjectRef <TService>(this.connectionInfo, instanceId, this.GetPublishedServices(instanceId).ToArray()));
                }

                var objectId             = RpcObjectId.NewId();
                var newPublishedServices = this.PublishInstanceCore_Locked(allServices, OwnedObject.CreateUnowned(serviceInstance), objectId, true);
                return(new RpcObjectRef <TService>(connectionInfo, objectId, newPublishedServices.ToArray()));
            }
        }
Exemplo n.º 29
0
        /// <summary>
        /// Removes the instance corresponding to the given name from the cache.
        /// The service itself remains registered and can be used to create other instances.
        /// </summary>
        /// <typeparam name="TInterface">The type of the instance to be removed.</typeparam>
        /// <param name="name">The name corresponding to the instance that must be removed.</param>
        public void Unregister <TInterface>(string name) where TInterface : class
        {
            var serviceType = typeof(TInterface);
            var key         = new InstanceKey(serviceType, name);

            _factories.Remove(key);
            if (name == null)
            {
                return;
            }

            if (!_namedInstances.TryGetValue(serviceType, out List <string> instances))
            {
                return;
            }
            instances.Remove(name);
            if (instances.Count == 0)
            {
                _namedInstances.Remove(serviceType);
            }
        }
        public IOwned <RpcSingletonRef <TService> > PublishSingleton <TService>(IOwned <TService> singletonService) where TService : class
        {
            if (singletonService == null)
            {
                throw new ArgumentNullException(nameof(singletonService));
            }

            var allServices = RpcBuilderUtil.GetAllServices(typeof(TService), false);

            this.TryRegisterServiceDefinitions(allServices, null);

            var publishedServices = this.VerifyPublishedServices(allServices);

            var connectionInfo = this.RetrieveConnectionInfo();

            lock (this.syncRoot)
            {
                var instanceKey = new InstanceKey(singletonService.Value);

                foreach (var serviceType in publishedServices.ServiceTypes)
                {
                    if (this.singletonServiceTypeToServiceImpl.ContainsKey(serviceType) || this.singletonServiceTypeToFactory.ContainsKey(serviceType))
                    {
                        throw new RpcDefinitionException($"A singleton for the type '{serviceType}' has already been published.");
                    }
                }

                this.singletonTypeToPublishedServices.Add(typeof(TService), publishedServices);
                var publishedInstance = new PublishedInstance(singletonService);
                foreach (var serviceType in publishedServices.ServiceTypes)
                {
                    this.singletonServiceTypeToServiceImpl.Add(serviceType, publishedInstance);
                }
            }

            return(OwnedObject.Create(new RpcSingletonRef <TService>(
                                          connectionInfo),
                                      () => this.UnpublishSingletonAsync <TService>()));
        }