public void StrategyDoesNotAttemptToDisposeInstanceIfItIsNotDisposable() { var instance = new object(); var reference = new InstanceReference { Instance = instance }; strategy.Deactivate(contextMock.Object, reference); }
public void InstanceIsRemovedFromCache() { var scope = new object(); var sword = new Sword(); var reference = new InstanceReference { Instance = sword }; var writeContext = new Mock<IContext>(); writeContext.SetupGet(x => x.Binding).Returns(bindingMock.Object); writeContext.SetupGet(x => x.HasInferredGenericArguments).Returns(true); writeContext.SetupGet(x => x.GenericArguments).Returns(new[] { typeof(int) }); writeContext.Setup(x => x.GetScope()).Returns(scope); cache.Remember(writeContext.Object, reference); var readContext = new Mock<IContext>(); readContext.SetupGet(x => x.Binding).Returns(bindingMock.Object); readContext.SetupGet(x => x.HasInferredGenericArguments).Returns(true); readContext.SetupGet(x => x.GenericArguments).Returns(new[] { typeof(int) }); readContext.Setup(x => x.GetScope()).Returns(scope); object instance1 = cache.TryGet(readContext.Object); instance1.ShouldBeSameAs(reference.Instance); bool result = cache.Release(instance1); result.ShouldBeTrue(); object instance2 = cache.TryGet(readContext.Object); instance2.ShouldBeNull(); }
public override void Activate( IContext context, InstanceReference reference ) { var messageBroker = context.Kernel.Components.Get<IMessageBroker>(); List<PublicationDirective> publications = context.Plan.GetAll<PublicationDirective>().ToList(); // I don't think this is needed in Ninject2 //if (publications.Count > 0) // context.ShouldTrackInstance = true; foreach ( PublicationDirective publication in publications ) { IMessageChannel channel = messageBroker.GetChannel( publication.Channel ); channel.AddPublication( reference.Instance, publication.Event ); } List<SubscriptionDirective> subscriptions = context.Plan.GetAll<SubscriptionDirective>().ToList(); // I don't think this is needed in Ninject2 //if (subscriptions.Count > 0) // context.ShouldTrackInstance = true; foreach ( SubscriptionDirective subscription in subscriptions ) { IMessageChannel channel = messageBroker.GetChannel( subscription.Channel ); channel.AddSubscription( reference.Instance, subscription.Injector, subscription.Thread ); } }
public void StrategyDoesNotAttemptToInitializeInstanceIfItIsNotInitializable() { var instance = new object(); var reference = new InstanceReference { Instance = instance }; strategy.Activate(contextMock.Object, reference); }
/// <summary> /// Activates the specified context. /// </summary> /// <param name="context">The context.</param> /// <param name="reference">The reference.</param> public override void Activate( IContext context, InstanceReference reference ) { if ( ShouldProxy( context ) ) { context.Kernel.Components.Get<IProxyFactory>().Wrap( context, reference ); } base.Activate( context, reference ); }
public void StrategyDisposesInstanceIfItIsDisposable() { var instance = new NotifiesWhenDisposed(); var reference = new InstanceReference { Instance = instance }; strategy.Deactivate(contextMock.Object, reference); instance.IsDisposed.ShouldBeTrue(); }
public void StrategyStartsInstanceIfItIsStartable() { var instance = new StartableObject(); var reference = new InstanceReference { Instance = instance }; strategy.Activate(contextMock.Object, reference); instance.WasStarted.Should().BeTrue(); }
public void StrategyInitializesInstanceIfItIsInitializable() { var instance = new InitializableObject(); var reference = new InstanceReference { Instance = instance }; strategy.Activate(contextMock.Object, reference); instance.WasInitialized.ShouldBeTrue(); }
/// <summary> /// Deactivates the instance in the specified context. /// </summary> /// <param name="context">The context.</param> /// <param name="reference">The instance reference.</param> public void Deactivate(IContext context, InstanceReference reference) { Ensure.ArgumentNotNull(context, "context"); if (!this.activationCache.IsDeactivated(reference.Instance)) { this.Strategies.Map(s => s.Deactivate(context, reference)); } }
/// <summary> /// Injects values into the properties as described by <see cref="MethodInjectionDirective"/>s /// contained in the plan. /// </summary> /// <param name="context">The context.</param> /// <param name="reference">A reference to the instance being activated.</param> public override void Activate(IContext context, InstanceReference reference) { foreach (var directive in context.Plan.GetAll<MethodInjectionDirective>()) { var arguments = directive.Targets.Select(target => target.ResolveWithin(context)); directive.Injector(reference.Instance, arguments.ToArray()); } }
public void CallsDeactivateOnStrategies() { var contextMock = new Mock<IContext>(); var reference = new InstanceReference(); this.Pipeline.Deactivate(contextMock.Object, reference); this.StrategyMocks.Map(mock => mock.Verify(x => x.Deactivate(contextMock.Object, reference))); }
public void Activate(IContext context, InstanceReference reference) { Type instanceType = reference.Instance.GetType(); LOGGER.Info("Component activation: " + instanceType.Name); if (!instanceType.IsAssignableFrom(typeof(Splashscreen))) { Splashscreen splashscreen = App.Kernel.Get<Splashscreen>(); splashscreen.SetProgress(string.Format("{0} loading...", instanceType.Name)); } }
/// <summary> /// Contributes to the deactivation of the instance in the specified context. /// </summary> /// <param name="context">The context.</param> /// <param name="reference">A reference to the instance being deactivated.</param> public override void Deactivate(IContext context, InstanceReference reference) { base.Deactivate(context, reference); if (this.Log != null) { this.Log.Info("Ninject binding deactivated: " + context.Binding.Service + " => " + reference.Instance.GetType()); } }
/// <summary> /// Activates the specified context. /// </summary> /// <param name="context">The context.</param> /// <param name="reference">The reference.</param> public override void Activate( IContext context, InstanceReference reference ) { if ( ShouldProxy( context ) ) { this.proxyFactory.Wrap( context, reference ); } base.Activate( context, reference ); }
/// <summary> /// Wraps the instance in the specified context in a proxy. /// </summary> /// <param name="context">The context in which the instance was activated.</param> /// <param name="reference">The <see cref="InstanceReference"/> to wrap.</param> public override void Wrap( IContext context, InstanceReference reference ) { var wrapper = new LinFuWrapper( Kernel, context, reference.Instance ); Type targetType = context.Request.Service; reference.Instance = targetType.IsInterface ? this._factory.CreateProxy(typeof(object), wrapper, context.Request.Service) : this._factory.CreateProxy(context.Request.Service, wrapper); }
/// <summary> /// Activates the specified context. /// </summary> /// <param name="context">The context.</param> /// <param name="reference">The reference.</param> public override void Activate(IContext context, InstanceReference reference) { var namedScopeParameters = context.Parameters.OfType<NamedScopeParameter>(); foreach (var namedScopeParameter in namedScopeParameters) { context.Kernel.Get<NamedScopeReference>( new NamedScopeReferenceScopeParameter(reference.Instance), new ConstructorArgument("scope", namedScopeParameter.Scope)); } }
/// <summary> /// Activates the instance in the specified context. /// </summary> /// <param name="context">The context.</param> /// <param name="reference">The instance reference.</param> public void Activate(IContext context, InstanceReference reference) { Contract.Requires(context != null); Contract.Requires(reference != null); if (!this.activationCache.IsActivated(reference.Instance)) { this.Strategies.Map(s => s.Activate(context, reference)); } }
public void WhenAlreadyActiavatedNothingHappens() { var contextMock = new Mock<IContext>(); var reference = new InstanceReference(); this.ActivationCacheMock.Setup(activationCache => activationCache.IsActivated(It.IsAny<object>())).Returns(true); this.Pipeline.Activate(contextMock.Object, reference); this.StrategyMocks.Map(mock => mock.Verify(x => x.Activate(contextMock.Object, reference), Times.Never())); }
/// <summary> /// Injects values into the properties as described by <see cref="PropertyInjectionDirective"/>s /// contained in the plan. /// </summary> /// <param name="context">The context.</param> /// <param name="reference">A reference to the instance being activated.</param> public override void Activate(IContext context, InstanceReference reference) { Ensure.ArgumentNotNull(context, "context"); Ensure.ArgumentNotNull(reference, "reference"); foreach (var directive in context.Plan.GetAll<PropertyInjectionDirective>()) { object value = GetValue(context, directive.Target); directive.Injector(reference.Instance, value); } }
public void ReturnsNullIfScopeIsNull() { var reference = new InstanceReference { Instance = new Sword() }; var context1 = CreateContext(new TestObject(42), this.bindingConfiguration); var context2 = CreateContext(null, this.bindingConfiguration); cache.Remember(context1, reference); object instance = cache.TryGet(context2); instance.Should().BeNull(); }
public void ReturnsCachedInstanceIfOneHasBeenAddedWithinSpecifiedScope() { var scope = new TestObject(42); var reference = new InstanceReference { Instance = new Sword() }; var context1 = CreateContext(scope, this.bindingConfiguration); var context2 = CreateContext(scope, this.bindingConfiguration); cache.Remember(context1, reference); object instance = cache.TryGet(context2); instance.Should().BeSameAs(reference.Instance); }
/// <summary> /// Injects values into the properties as described by <see cref="PropertyInjectionDirective"/>s /// contained in the plan. /// </summary> /// <param name="context">The context.</param> /// <param name="reference">A reference to the instance being activated.</param> public override void Activate(IContext context, InstanceReference reference) { var propertyValues = context.Parameters.OfType<IPropertyValue>().ToList(); foreach (var directive in context.Plan.GetAll<PropertyInjectionDirective>()) { object value = this.GetValue(context, directive.Target, propertyValues); directive.Injector(reference.Instance, value); } this.AssignPropertyOverrides(context, reference, propertyValues); }
/// <summary> /// Wraps the instance in the specified context in a proxy. /// </summary> /// <param name="context">The context in which the instance was activated.</param> /// <param name="reference">The <see cref="InstanceReference"/> to wrap.</param> public override void Wrap( IContext context, InstanceReference reference ) { var wrapper = new LinFuWrapper( Kernel, context, reference.Instance ); Type targetType = context.Request.Service; Type[] additionalInterfaces = context.Parameters.OfType<AdditionalInterfaces>().Any() ? context.Parameters.OfType<AdditionalInterfaces>().First().GetValue(context, null) as Type[] : new Type[] { }; reference.Instance = targetType.IsInterface ? this._factory.CreateProxy(typeof(object), wrapper, new[] { targetType }.Concat(additionalInterfaces).ToArray()) : this._factory.CreateProxy(targetType, wrapper, additionalInterfaces); }
/// <summary> /// Activates the <see cref="DbSet{T}"/>. /// </summary> /// <param name="context">The context.</param> /// <param name="reference">The reference to the instance being activated.</param> public sealed override void Activate(IContext context, InstanceReference reference) { if (reference == null) { throw new ArgumentNullException("reference"); } if (context.Request.Service.IsGenericType() && context.Request.Service.GetGenericTypeDefinition() == typeof(DbSet<>)) { this.ActivateDbSet(context, reference); } }
/// <summary> /// Activates the <see cref="DbContext"/>. /// </summary> /// <param name="context">The context.</param> /// <param name="reference">The reference to the instance being activated.</param> public sealed override void Activate(IContext context, InstanceReference reference) { if (reference == null) { throw new ArgumentNullException("reference"); } if (typeof(DbContext).IsAssignableFrom(context.Request.Service)) { this.ActivateDbContext(context, reference); } }
/// <summary> /// Unwraps the instance in the specified context. /// </summary> /// <param name="context">The context in which the instance was activated.</param> /// <param name="reference">The <see cref="InstanceReference"/> to unwrap.</param> public override void Unwrap( IContext context, InstanceReference reference ) { var proxy = reference.Instance as IProxy; if ( proxy == null ) { return; } var wrapper = proxy.Interceptor as LinFuWrapper; reference.Instance = ( wrapper == null ) ? proxy : wrapper.Instance; }
/// <summary> /// Contributes to the activation of the instance in the specified context. /// </summary> /// <param name="context">The context.</param> /// <param name="reference">A reference to the instance being activated.</param> public override void Activate(IContext context, InstanceReference reference) { if (reference.Instance is ILogger && this.Log == null) { this.Log = (ILogger)reference.Instance; } base.Activate(context, reference); if (this.Log != null) { this.Log.Info("Ninject binding activated: " + context.Binding.Service + " => " + reference.Instance.GetType()); } }
public void ReturnsTrueIfInstanceIsTracked() { var scope = new TestObject(42); var instance = new Sword(); var reference = new InstanceReference { Instance = instance }; var writeContext = CreateContext(scope, this.bindingConfiguration, typeof(int)); cache.Remember(writeContext, reference); bool result = cache.Release(instance); result.Should().BeTrue(); }
public void Deactivate_NotTransparantProxy_Disposable() { var initializableMock = new Mock <IDisposable>(MockBehavior.Strict); var reference = new InstanceReference { Instance = initializableMock.Object }; initializableMock.Setup(p => p.Dispose()); _strategy.Deactivate(_contextMock.Object, reference); Assert.Same(initializableMock.Object, reference.Instance); initializableMock.Verify(p => p.Dispose(), Times.Once); }
public void ReturnsCachedInstanceIfOneHasBeenAddedWithinSpecifiedScope() { var scope = new object(); var reference = new InstanceReference { Instance = new Sword() }; var contextMock1 = CreateContextMock(scope, bindingMock.Object); var contextMock2 = CreateContextMock(scope, bindingMock.Object); cache.Remember(contextMock1.Object, reference); object instance = cache.TryGet(contextMock2.Object); instance.ShouldBeSameAs(reference.Instance); }
public void ReturnsInstanceIfOneHasBeenCachedWithSameGenericParameters() { var scope = new TestObject(42); var reference = new InstanceReference { Instance = new Sword() }; var context1 = CreateContext(scope, this.bindingConfiguration, typeof(int)); var context2 = CreateContext(scope, this.bindingConfiguration, typeof(int)); cache.Remember(context1, reference); object instance = cache.TryGet(context2); instance.Should().BeSameAs(reference.Instance); }
/// <summary>Snippet for GetHealth</summary> public void GetHealth() { // Snippet: GetHealth(string, string, string, InstanceReference, CallSettings) // Create client TargetPoolsClient targetPoolsClient = TargetPoolsClient.Create(); // Initialize request argument(s) string project = ""; string region = ""; string targetPool = ""; InstanceReference instanceReferenceResource = new InstanceReference(); // Make the request TargetPoolInstanceHealth response = targetPoolsClient.GetHealth(project, region, targetPool, instanceReferenceResource); // End snippet }
public void Remember_ContextAndScopeAndReference_ShouldThrowArgumentNullExceptionWhenScopeIsNull() { var context = _contextMock1.Object; const object scope = null; var instanceReference = new InstanceReference { Instance = new object() }; var cache = CreateCache(); var actual = Assert.Throws <ArgumentNullException>(() => cache.Remember(context, scope, instanceReference)); Assert.Null(actual.InnerException); Assert.Equal(nameof(scope), actual.ParamName); }
public void ReturnsNullIfInstanceAddedToCacheHasDifferentGenericParameters() { var scope = new object(); var reference = new InstanceReference { Instance = new Sword() }; var contextMock1 = CreateContextMock(scope, bindingMock.Object, typeof(int)); var contextMock2 = CreateContextMock(scope, bindingMock.Object, typeof(double)); cache.Remember(contextMock1.Object, reference); object instance = cache.TryGet(contextMock2.Object); instance.ShouldBeNull(); }
public void ReturnsInstanceIfOneHasBeenCachedWithSameGenericParameters() { var scope = new object(); var reference = new InstanceReference { Instance = new Sword() }; var contextMock1 = CreateContextMock(scope, bindingMock.Object, typeof(int)); var contextMock2 = CreateContextMock(scope, bindingMock.Object, typeof(int)); cache.Remember(contextMock1.Object, reference); object instance = cache.TryGet(contextMock2.Object); instance.ShouldBeSameAs(reference.Instance); }
public void ReturnsNullIfInstanceAddedToCacheHasDifferentGenericParameters() { var scope = new TestObject(42); var reference = new InstanceReference { Instance = new Sword() }; var context1 = CreateContext(scope, this.bindingConfiguration, typeof(int)); var context2 = CreateContext(scope, this.bindingConfiguration, typeof(double)); cache.Remember(context1, reference); object instance = cache.TryGet(context2); instance.Should().BeNull(); }
public void ReturnsTrueIfInstanceIsTracked() { var scope = new object(); var instance = new Sword(); var reference = new InstanceReference { Instance = instance }; var writeContext = CreateContextMock(scope, bindingMock.Object, typeof(int)); cache.Remember(writeContext.Object, reference); bool result = cache.Release(instance); result.ShouldBeTrue(); }
public void Activate_NotTransparantProxy_Startable() { var startableMock = new Mock <IStartable>(MockBehavior.Strict); var reference = new InstanceReference { Instance = startableMock.Object }; startableMock.Setup(p => p.Start()); _strategy.Activate(_contextMock.Object, reference); Assert.Same(startableMock.Object, reference.Instance); startableMock.Verify(p => p.Start(), Times.Once); }
/// <summary> /// Creates and wraps the reference type in a Castle proxy /// </summary> /// <param name="context">The context.</param> /// <param name="reference">The reference.</param> public override void Activate(IContext context, InstanceReference reference) { if (reference.Instance as IInterceptor == null && reference.Instance as INinjectAspectConfiguration == null) { Configuration = context.Kernel.Get<INinjectAspectConfiguration>().Configuration; QueryTargetType(reference.Instance.GetType()); var interceptors = context.Kernel.GetAll<IInterceptor>(); reference.Instance = AspectUtility.CreateProxy(_targetInterface, reference.Instance, interceptors.ToArray()); } base.Activate(context, reference); }
/// <summary> /// Injects values into the properties as described by <see cref="PropertyInjectionDirective"/>s /// contained in the plan. /// </summary> /// <param name="context">The context.</param> /// <param name="reference">A reference to the instance being activated.</param> public override void Activate(IContext context, InstanceReference reference) { Ensure.ArgumentNotNull(context, "context"); Ensure.ArgumentNotNull(reference, "reference"); var propertyValues = context.Parameters.OfType <IPropertyValue>().ToList(); foreach (var directive in context.Plan.GetAll <PropertyInjectionDirective>()) { var value = this.GetValue(context, directive.Target, propertyValues); directive.Injector(reference.Instance, value); } this.AssignPropertyOverrides(context, reference, propertyValues); }
public void CachedObjectsAreReleased() { var scopeMock = new Mock <INotifyWhenDisposed>(); var sword = new Sword(); var reference = new InstanceReference { Instance = sword }; var context = CreateContext(scopeMock.Object, this.bindingConfiguration); cache.Remember(context, reference); scopeMock.Raise(scope => scope.Disposed += null, EventArgs.Empty); object instance = cache.TryGet(context); instance.Should().BeNull(); }
internal ConfiguredTaskAwaiter(Task task, bool continueOnSourceContext, InstanceReference instanceReference) { this.task = task; this.continueOnSourceContext = continueOnSourceContext; this.instanceReference = instanceReference; this.thisSetter = null; if (instanceReference != null) { if (InstanceSynchronizationContext.GetRegisteredActivity(instanceReference) == null) { throw new TaskSchedulerException("ConfiguredTaskAwaiter called while static SynchronizationContext.SetSynchronizationContext(...) is not called."); } } }
/// <summary> /// Injects values into the properties as described by <see cref="PropertyInjectionDirective" />s /// contained in the plan. /// </summary> /// <param name="context">The context.</param> /// <param name="reference">A reference to the instance being activated.</param> public override void Activate(IContext context, InstanceReference reference) { Ensure.ArgumentNotNull(context, "context"); Ensure.ArgumentNotNull(reference, "reference"); var propertyValues = context.Parameters.OfType<IPropertyValue>().ToList(); foreach (var directive in context.Plan.GetAll<PropertyInjectionDirective>()) { var value = GetValue(context, directive.Target, propertyValues); directive.Injector(reference.Instance, value); } AssignProperyOverrides(context, reference, propertyValues); }
/// <summary> /// Creates and wraps the reference type in a Castle proxy /// </summary> /// <param name="context">The context.</param> /// <param name="reference">The instance reference.</param> public override void Activate(IContext context, InstanceReference reference) { // Don't try to IInterceptor or MasterProxy instances. if (reference.Instance as IInterceptor == null && reference.Instance.GetType() != typeof(MasterProxy)) // as INinjectAspectConfiguration == null) { var proxy = context.Kernel.Get <IMasterProxy>(); // Only build a proxy for decorated types if (reference.Instance.IsDecorated(proxy.Configuration)) { reference.Instance = _proxyFactory.CreateProxy(reference.Instance, proxy); } } base.Activate(context, reference); }
/// <summary> /// Creates and wraps the reference type in a Castle proxy /// </summary> /// <param name="context">The context.</param> /// <param name="reference">The instance reference.</param> public override void Activate(IContext context, InstanceReference reference) { // Don't try to IInterceptor or MasterProxy instances. if (reference.Instance as IInterceptor == null && reference.Instance.GetType() != typeof(MasterProxy)) // as INinjectAspectConfiguration == null) { var proxy = context.Kernel.Get<IMasterProxy>(); // Only build a proxy for decorated types if (reference.Instance.IsDecorated(proxy.Configuration)) { reference.Instance = _proxyFactory.CreateProxy(reference.Instance, proxy); } } base.Activate(context, reference); }
public void Remember_ContextAndScopeAndReference_ShouldKeepWeakReferenceToScope() { var context = _contextMock1.Object; var cache = CreateCache(); var instance = new object(); var instanceReference = new InstanceReference { Instance = instance }; var scope = Remember(cache, _contextMock1, _bindingConfigurationMock1.Object, instanceReference); GC.Collect(); GC.WaitForPendingFinalizers(); Assert.False(scope.IsAlive); }
/// <summary> /// Injects values into the properties as described by /// <see cref="T:Ninject.Planning.Directives.PropertyInjectionDirective"/>s /// contained in the plan. /// </summary> /// <param name="context">The context.</param> /// <param name="reference">A reference to the instance being /// activated.</param> /// <exception cref="ArgumentNullException">The <paramref name="context"/> parameter is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">The <paramref name="reference"/> parameter is <c>null</c>.</exception> public override void Activate(IContext context, InstanceReference reference) { if (this.activatedInstances.Contains(reference.Instance)) { return; // "Skip" standard activation as it was already done! } // Keep track of non-transient activations... // Note: Maybe this should be // ScopeCallback == StandardScopeCallbacks.Singleton if (context.Binding.ScopeCallback != StandardScopeCallbacks.Transient) { this.activatedInstances.Add(reference.Instance); } base.Activate(context, reference); }
/// <summary>Snippet for GetHealthAsync</summary> public async Task GetHealthAsync() { // Snippet: GetHealthAsync(string, string, string, InstanceReference, CallSettings) // Additional: GetHealthAsync(string, string, string, InstanceReference, CancellationToken) // Create client TargetPoolsClient targetPoolsClient = await TargetPoolsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; string targetPool = ""; InstanceReference instanceReferenceResource = new InstanceReference(); // Make the request TargetPoolInstanceHealth response = await targetPoolsClient.GetHealthAsync(project, region, targetPool, instanceReferenceResource); // End snippet }
public void Activate_TransparentProxy_NotStartable() { using (var server = new RemotingServer()) using (var client = new RemotingClient()) { server.RegisterActivatedService(typeof(Monk)); var notStartable = client.GetService <Monk>(); var reference = new InstanceReference { Instance = notStartable }; _strategy.Activate(_contextMock.Object, reference); Assert.Same(notStartable, reference.Instance); } }
public void Release_NotNullInstance_OnlyCacheEntriesFound() { var scope1 = new object(); var scope2 = new object(); var cache = CreateCache(); var notNullInstanceReference1 = new InstanceReference { Instance = new object() }; var notNullInstanceReference2 = new InstanceReference { Instance = new object() }; var notNullInstanceReference3 = new InstanceReference { Instance = new object() }; _contextMock1.Setup(p => p.Binding).Returns(_bindingMock1.Object); _bindingMock1.Setup(p => p.BindingConfiguration).Returns(_bindingConfigurationMock1.Object); _contextMock2.Setup(p => p.Binding).Returns(_bindingMock2.Object); _bindingMock2.Setup(p => p.BindingConfiguration).Returns(_bindingConfigurationMock2.Object); cache.Remember(_contextMock1.Object, scope1, notNullInstanceReference1); cache.Remember(_contextMock1.Object, scope2, notNullInstanceReference2); cache.Remember(_contextMock2.Object, scope1, notNullInstanceReference1); cache.Remember(_contextMock2.Object, scope2, notNullInstanceReference3); Assert.Equal(4, cache.Count); _pipelineMock.Setup(p => p.Deactivate(_contextMock1.Object, notNullInstanceReference1)); _pipelineMock.Setup(p => p.Deactivate(_contextMock2.Object, notNullInstanceReference1)); var actual = cache.Release(notNullInstanceReference1.Instance); Assert.True(actual); _pipelineMock.Verify(p => p.Deactivate(_contextMock1.Object, notNullInstanceReference1), Times.Once()); _pipelineMock.Verify(p => p.Deactivate(_contextMock2.Object, notNullInstanceReference1), Times.Once()); Assert.Equal(2, cache.Count); _contextMock1.Setup(p => p.HasInferredGenericArguments).Returns(false); _contextMock2.Setup(p => p.HasInferredGenericArguments).Returns(false); Assert.Same(notNullInstanceReference2.Instance, cache.TryGet(_contextMock1.Object, scope2)); Assert.Same(notNullInstanceReference3.Instance, cache.TryGet(_contextMock2.Object, scope2)); }
private void UpdateInstanceIDBox() { Instances.Clear(); InstanceIDBox.Items.Clear(); if (CvmInstanceList.Count() != 0) { InstanceIDBox.Items.Add("=======Cvm======"); Instances.Add(new InstanceReference() { InstanceType = "Tag" }); for (int i1 = 0; i1 < CvmInstanceList.Count; i1++) { TencentCloud.Cvm.V20170312.Models.Instance i = CvmInstanceList[i1]; InstanceReference insref = new InstanceReference(); insref.InstanceID = i.InstanceId; insref.InstanceType = "Cvm"; insref.InstanceListIndex = i1; Instances.Add(insref); InstanceIDBox.Items.Add($"{i.InstanceId}({i.InstanceName})"); } } if (LighthouseInstanceList.Count != 0) { InstanceIDBox.Items.Add("===LightHouse==="); Instances.Add(new InstanceReference() { InstanceType = "Tag" }); for (int i1 = 0; i1 < LighthouseInstanceList.Count; i1++) { TencentCloud.Lighthouse.V20200324.Models.Instance i = LighthouseInstanceList[i1]; InstanceReference insref = new InstanceReference(); insref.InstanceID = i.InstanceId; insref.InstanceType = "Lighthouse"; insref.InstanceListIndex = i1; Instances.Add(insref); InstanceIDBox.Items.Add($"{i.InstanceId}({i.InstanceName})"); } } }
/// <summary> /// Injects values into the properties as described by <see cref="PropertyInjectionDirective"/>s /// contained in the plan. /// </summary> /// <param name="context">The context.</param> /// <param name="reference">A reference to the instance being activated.</param> /// <exception cref="ArgumentNullException"><paramref name="context"/> is <see langword="null"/>.</exception> /// <exception cref="ArgumentNullException"><paramref name="reference"/> is <see langword="null"/>.</exception> public override void Activate(IContext context, InstanceReference reference) { Ensure.ArgumentNotNull(context, nameof(context)); Ensure.ArgumentNotNull(reference, nameof(reference)); var propertyValues = GetPropertyValues(context.Parameters); foreach (var directive in context.Plan.GetAll <PropertyInjectionDirective>()) { var value = this.GetValue(context, directive.Target, propertyValues); directive.Injector(reference.Instance, value); } if (propertyValues.Count > 0) { this.AssignPropertyOverrides(context, reference, propertyValues); } }
public void WhenNoScopeIsDefinedAllEntriesAreReleased() { var sword = new Sword(); var reference = new InstanceReference { Instance = sword }; var context1 = CreateContextMock(new object(), bindingMock.Object); var context2 = CreateContextMock(new object(), bindingMock.Object); cache.Remember(context1.Object, reference); cache.Remember(context2.Object, reference); cache.Clear(); var instance1 = cache.TryGet(context1.Object); var instance2 = cache.TryGet(context2.Object); instance1.ShouldBeNull(); instance2.ShouldBeNull(); }
/// <summary> /// Applies user supplied override values to instance properties. /// </summary> /// <param name="context">The context.</param> /// <param name="reference">A reference to the instance being activated.</param> /// <param name="propertyValues">The parameter override value accessors.</param> /// <exception cref="ActivationException">A given <see cref="IPropertyValue"/> cannot be resolved to a property of the specified instance.</exception> private void AssignPropertyOverrides(IContext context, InstanceReference reference, List <IPropertyValue> propertyValues) { var properties = reference.Instance.GetType().GetProperties(this.Flags); foreach (var propertyValue in propertyValues) { var propertyInfo = FindPropertyByName(properties, propertyValue.Name, StringComparison.Ordinal); if (propertyInfo == null) { throw new ActivationException(this.exceptionFormatter.CouldNotResolvePropertyForValueInjection(context.Request, propertyValue.Name)); } var target = new PropertyInjectionDirective(propertyInfo, this.injectorFactory.Create(propertyInfo)); var value = propertyValue.GetValue(context, target.Target); target.Injector(reference.Instance, value); } }
/// <summary> /// Injects the specified existing instance, without managing its lifecycle. /// </summary> /// <param name="instance">The instance to inject.</param> /// <param name="parameters">The parameters to pass to the request.</param> /// <exception cref="ArgumentNullException"><paramref name="instance"/> is <see langword="null"/>.</exception> /// <exception cref="ArgumentNullException"><paramref name="parameters"/> is <see langword="null"/>.</exception> public void Inject(object instance, params IParameter[] parameters) { Ensure.ArgumentNotNull(instance, nameof(instance)); var service = instance.GetType(); var binding = new Binding(service); var request = this.CreateRequest(service, null, parameters, false, false); var context = this.CreateContext(request, binding); context.Plan = this.planner.GetPlan(service); var reference = new InstanceReference { Instance = instance }; this.pipeline.Activate(context, reference); }
public void Activate_TransparentProxy_Disposable() { using (var server = new RemotingServer()) using (var client = new RemotingClient()) { server.RegisterActivatedService(typeof(Disposable)); var initializable = client.GetService <Disposable>(); var reference = new InstanceReference { Instance = initializable }; _strategy.Activate(_contextMock.Object, reference); Assert.Equal(0, initializable.DisposeCount); Assert.Same(initializable, reference.Instance); } }
public void WhenNoScopeIsDefinedAllEntriesAreReleased() { var sword = new Sword(); var reference = new InstanceReference { Instance = sword }; var context1 = CreateContext(new TestObject(42), this.bindingConfiguration); var context2 = CreateContext(new TestObject(42), this.bindingConfiguration); cache.Remember(context1, reference); cache.Remember(context2, reference); cache.Clear(); var instance1 = cache.TryGet(context1); var instance2 = cache.TryGet(context2); instance1.Should().BeNull(); instance2.Should().BeNull(); }
public void IsInstanceOf_NotTransparentProxy_IsAnInstanceOf() { var instance = new ShortSword(); var reference = new InstanceReference { Instance = instance }; Assert.True(reference.IsInstanceOf <ShortSword>(out var shortSword)); Assert.Same(instance, shortSword); Assert.True(reference.IsInstanceOf <Sword>(out var sword)); Assert.Same(instance, sword); Assert.True(reference.IsInstanceOf <IWeapon>(out var weapon)); Assert.Same(instance, weapon); Assert.True(reference.IsInstanceOf <IWeapon>(out var obj)); Assert.Same(instance, obj); }
public void IsInstanceOf_TransparentProxy_IsNotAnInstanceOf() { using (var server = new RemotingServer()) using (var client = new RemotingClient()) { server.RegisterActivatedService(typeof(Disposable)); var instance = client.GetService <Disposable>(); var reference = new InstanceReference { Instance = instance }; Assert.False(reference.IsInstanceOf <ICleric>(out var cleric)); Assert.Null(cleric); Assert.False(reference.IsInstanceOf <Monk>(out var monk)); Assert.Null(monk); } }