internal static ILifetimeScope GetScope()
    {
        var context = HttpContext.Current;

        if (initialized)
        {
            return(GetScope(context, createIfNotPresent: true));
        }
        else if (allowDefaultScopeOutOfHttpContext && !IsRequestAvailable())
        {
            // We're not running within a Http Request.  If the option has been set to allow a normal scope to
            // be used in this situation, we'll use that instead
            ILifetimeScope scope = CallContextLifetimeScope.ObtainCurrentScope();
            if (scope == null)
            {
                throw new InvalidOperationException("Not running within a Http Request, and no Scope was manually created.  Either run from within a request, or call container.BeginScope()");
            }
            return(scope);
        }
        else if (context == null)
        {
            throw new InvalidOperationException(
                      "HttpContext.Current is null. PerWebRequestLifestyle can only be used in ASP.Net");
        }
        else
        {
            EnsureInitialized();
            return(GetScope(context, createIfNotPresent: true));
        }
    }
        public void Install(Castle.Windsor.IWindsorContainer container, Castle.MicroKernel.SubSystems.Configuration.IConfigurationStore store)
        {
            container.Register(
                Component.For <IServiceBus>()
                .UsingFactoryMethod(() =>
                                    ServiceBusFactory.New(sbc =>
            {
                sbc.UseMsmq();
                sbc.VerifyMsmqConfiguration();

                sbc.UseMulticastSubscriptionClient();

                sbc.ReceiveFrom("msmq://localhost/web");
                sbc.SetCreateMissingQueues(true);
                sbc.UseJsonSerializer();

                sbc.Subscribe(subs => subs.LoadFrom(container));

                sbc.BeforeConsumingMessage(() => container.BeginScope());
                sbc.AfterConsumingMessage(() => CallContextLifetimeScope.ObtainCurrentScope().Dispose());
            })
                                    )
                .LifestyleSingleton()
                );
        }
示例#3
0
        static IPublishEndpoint GetCurrentPublishEndpoint(IKernel context)
        {
            var currentScope = CallContextLifetimeScope.ObtainCurrentScope();

            return(currentScope != null
                ? context.Resolve <ConsumeContext>()
                : (IPublishEndpoint)context.Resolve <IBus>());
        }
示例#4
0
        static ISendEndpointProvider GetCurrentSendEndpointProvider(IKernel context)
        {
            var currentScope = CallContextLifetimeScope.ObtainCurrentScope();

            return(currentScope != null
                ? context.Resolve <ConsumeContext>()
                : (ISendEndpointProvider)context.Resolve <IBus>());
        }
示例#5
0
        public ILifetimeScope GetScope(CreationContext context)
        {
            if (CallContextLifetimeScope.ObtainCurrentScope() is MessageLifetimeScope lifetimeScope)
            {
                return(lifetimeScope);
            }

            throw new InvalidOperationException("MessageScope was not available. Add UseMessageScope() to your receive endpoint to enable message scope");
        }
示例#6
0
        private static IDisposable RequireScope()
        {
            var current = CallContextLifetimeScope.ObtainCurrentScope();

            if (current == null)
            {
                return(BeginScope());
            }
            return(null);            // Return null, not the parent otherwise you'll cause premature disposal
        }
示例#7
0
        public static IDisposable CreateNewOrUseExistingMessageScope(this IKernel kernel)
        {
            var currentScope = CallContextLifetimeScope.ObtainCurrentScope();

            if (currentScope is MessageLifetimeScope)
            {
                return(null);
            }

            return(kernel.BeginScope());
        }
        public void Dispose()
        {
            CallContextLifetimeScope contextLifetimeScope = CallContextLifetimeScope.ObtainCurrentScope();

            if (contextLifetimeScope == null)
            {
                this._webRequestScopeAccessor.Dispose();
                return;
            }
            contextLifetimeScope.Dispose();
        }
        public static IDisposable CreateNewOrUseExistingMessageScope(this IKernel kernel)
        {
            var currentScope = CallContextLifetimeScope.ObtainCurrentScope();

            if (currentScope is MessageLifetimeScope scope)
            {
                kernel.Resolve <ScopedConsumeContextProvider>().SetContext(scope.ConsumeContext);
                return(null);
            }

            return(kernel.BeginScope());
        }
 protected virtual void Dispose(bool disposing)
 {
     if (!disposed)
     {
         disposed = true;
         var scope = CallContextLifetimeScope.ObtainCurrentScope();
         if (scope != null)
         {
             scope.Dispose();
         }
     }
 }
示例#11
0
        public void Starts_Windsor_scope_when_container_is_created()
        {
            var globalContainer   = new ObjectContainer();
            var scenarioContainer = new ObjectContainer(globalContainer);

            var beforeScope = CallContextLifetimeScope.ObtainCurrentScope();

            CreateContainerViaPlugin(globalContainer, scenarioContainer);
            var afterScope = CallContextLifetimeScope.ObtainCurrentScope();

            beforeScope.Should().BeNull();
            afterScope.Should().NotBeNull();
        }
        public void RegisterRequestClient <T>(Uri destinationAddress, RequestTimeout timeout = default)
            where T : class
        {
            _container.Register(Component.For <IRequestClient <T> >().UsingFactoryMethod(kernel =>
            {
                var clientFactory = kernel.Resolve <IClientFactory>();

                var currentScope = CallContextLifetimeScope.ObtainCurrentScope();
                return((currentScope != null)
                    ? clientFactory.CreateRequestClient <T>(kernel.Resolve <ConsumeContext>(), destinationAddress, timeout)
                    : clientFactory.CreateRequestClient <T>(destinationAddress, timeout));
            }));
        }
 async Task IFilter <ConsumeContext> .Send(ConsumeContext context, IPipe <ConsumeContext> next)
 {
     if (CallContextLifetimeScope.ObtainCurrentScope() is MessageLifetimeScope)
     {
         await next.Send(context).ConfigureAwait(false);
     }
     else
     {
         using (new MessageLifetimeScope(context))
         {
             await next.Send(context).ConfigureAwait(false);
         }
     }
 }
        public ILifetimeScope GetScope(CreationContext context)
        {
            CallContextLifetimeScope contextLifetimeScope = CallContextLifetimeScope.ObtainCurrentScope();

            if (contextLifetimeScope != null)
            {
                return((ILifetimeScope)contextLifetimeScope);
            }
            if (HttpContext.Current != null && PerWebRequestLifestyleModuleUtils.IsInitialized)
            {
                return(this._webRequestScopeAccessor.GetScope(context));
            }
            throw new InvalidOperationException("Naither Http nor CallContext scope was available. Did you forget to call container.BeginScope()?");
        }
        /// <summary>
        /// Get all NancyModule implementation instances
        /// </summary>
        /// <param name="context">The current context</param>
        /// <returns>An <see cref="IEnumerable{T}"/> instance containing <see cref="NancyModule"/> instances.</returns>
        public override IEnumerable <INancyModule> GetAllModules(NancyContext context)
        {
            var currentScope =
                CallContextLifetimeScope.ObtainCurrentScope();

            if (currentScope != null)
            {
                return(this.ApplicationContainer.ResolveAll <INancyModule>());
            }

            using (this.ApplicationContainer.BeginScope())
            {
                return(this.ApplicationContainer.ResolveAll <INancyModule>());
            }
        }
        /// <summary>
        /// Retrieves a specific <see cref="INancyModule"/> implementation - should be per-request lifetime
        /// </summary>
        /// <param name="moduleType">Module type</param>
        /// <param name="context">The current context</param>
        /// <returns>The <see cref="INancyModule"/> instance</returns>
        public override INancyModule GetModule(Type moduleType, NancyContext context)
        {
            var currentScope =
                CallContextLifetimeScope.ObtainCurrentScope();

            if (currentScope != null)
            {
                return(this.ApplicationContainer.Resolve <INancyModule>(moduleType.FullName));
            }

            using (this.ApplicationContainer.BeginScope())
            {
                return(this.ApplicationContainer.Resolve <INancyModule>(moduleType.FullName));
            }
        }
示例#17
0
        public void Windsor_scope_ends_when_scenario_ends()
        {
            var globalContainer   = new ObjectContainer();
            var scenarioContainer = new ObjectContainer(globalContainer);

            CreateContainerViaPlugin(globalContainer, scenarioContainer);

            var activeScope = CallContextLifetimeScope.ObtainCurrentScope();

            scenarioContainer.Dispose();
            var endedScope = CallContextLifetimeScope.ObtainCurrentScope();

            activeScope.Should().NotBeNull();
            endedScope.Should().BeNull();
        }
示例#18
0
        /// <summary>
        /// Retrieves a specific <see cref="NancyModule"/> implementation based on its key
        /// </summary>
        /// <param name="moduleKey">Module key</param>
        /// <param name="context">The current context</param>
        /// <returns>The <see cref="NancyModule"/> instance that was retrived by the <paramref name="moduleKey"/> parameter.</returns>
        public override NancyModule GetModuleByKey(string moduleKey, NancyContext context)
        {
            var currentScope =
                CallContextLifetimeScope.ObtainCurrentScope();

            if (currentScope != null)
            {
                return(this.ApplicationContainer.Resolve <NancyModule>(moduleKey));
            }

            using (this.ApplicationContainer.BeginScope())
            {
                return(this.ApplicationContainer.Resolve <NancyModule>(moduleKey));
            }
        }
        /// <inheritdoc />
        public override async Task Invoke(IIncomingPhysicalMessageContext context, Func <Task> next)
        {
            CallContextLifetimeScope currentScope = CallContextLifetimeScope.ObtainCurrentScope();

            if (currentScope != null)
            {
                throw new InternalProgrammingError($"Didn't expect a Castle-Windsor scope yet, for MessageId: {context.MessageId}");
            }

            using (Kernel.BeginScope())
            {
                ISession session = Kernel.Resolve <ISession>();
                try
                {
                    Contract.Assert(session.IsOpen);
                    ITransaction transaction = session.BeginTransaction(IsolationLevel.Unspecified);
                    try
                    {
                        MessageContextAccessor.MessageContext = new RequestMessageContext(context.MessageHeaders);
                        try
                        {
                            await next().ConfigureAwait(false);
                        }
                        finally
                        {
                            MessageContextAccessor.MessageContext = null;
                        }

                        Logger.Info(() => $"Flush and commit our request transaction, for MessageId: {context.MessageId}.");
                        await session.FlushAsync().ConfigureAwait(false);

                        await transaction.CommitAsync().ConfigureAwait(false);
                    }
                    catch (OperationCanceledException)
                    {
                        Logger.Info($"Operation cancelled, for MessageId: {context.MessageId}.");
                        throw;
                    }
                    catch (MessageDeserializationException)
                    {
                        Logger.Info($"Message deserialization exception for MessageId: {context.MessageId}.");
                        throw;
                    }
                    catch (Exception e)
                    {
                        Logger.Error($"While flush and committing for MessageId: {context.MessageId}.", e);
                        throw;
                    }
                    finally
                    {
                        if (transaction.IsActive)
                        {
                            Logger.Error($"Rolling back transaction for MessageId: {context.MessageId}.");
                            await transaction.RollbackAsync().ConfigureAwait(false);
                        }
                    }
                }
                finally
                {
                    Kernel.ReleaseComponent(session);
                }
            }
        }