Ejemplo n.º 1
1
        public void Init() {
            _settingsA = new ShellSettings { Name = "Alpha" };
            _settingsB = new ShellSettings { Name = "Beta", };
            _routes = new RouteCollection();

            var rootBuilder = new ContainerBuilder();
            rootBuilder.Register(ctx => _routes);
            rootBuilder.RegisterType<ShellRoute>().InstancePerDependency();
            rootBuilder.RegisterType<RunningShellTable>().As<IRunningShellTable>().SingleInstance();
            rootBuilder.RegisterModule(new WorkContextModule());
            rootBuilder.RegisterType<WorkContextAccessor>().As<IWorkContextAccessor>().InstancePerMatchingLifetimeScope("shell");
            rootBuilder.RegisterType<HttpContextAccessor>().As<IHttpContextAccessor>();
            rootBuilder.RegisterType<ExtensionManager>().As<IExtensionManager>();
            rootBuilder.RegisterType<StubCacheManager>().As<ICacheManager>();
            rootBuilder.RegisterType<StubAsyncTokenProvider>().As<IAsyncTokenProvider>();
            rootBuilder.RegisterType<StubParallelCacheContext>().As<IParallelCacheContext>();

            _rootContainer = rootBuilder.Build();

            _containerA = _rootContainer.BeginLifetimeScope(
                "shell",
                builder => {
                    builder.Register(ctx => _settingsA);
                    builder.RegisterType<RoutePublisher>().As<IRoutePublisher>().InstancePerMatchingLifetimeScope("shell");
                });

            _containerB = _rootContainer.BeginLifetimeScope(
                "shell",
                builder => {
                    builder.Register(ctx => _settingsB);
                    builder.RegisterType<RoutePublisher>().As<IRoutePublisher>().InstancePerMatchingLifetimeScope("shell");
                });
        }
        public ApplicationController(ILifetimeScope rootScope)
        {
            Guard.NotNull("rootScope", rootScope);

            this.rootScope = rootScope;
            mainWindowLock = new Object();
        }
 /// <summary>
 /// Gets a nested lifetime scope that services can be resolved from.
 /// </summary>
 /// <param name="container">The parent container.</param>
 /// <param name="configurationAction">Action on a <see cref="ContainerBuilder"/>
 /// that adds component registations visible only in nested lifetime scopes.</param>
 /// <returns>A new or existing nested lifetime scope.</returns>
 public static ILifetimeScope GetLifetimeScope(ILifetimeScope container, Action<ContainerBuilder> configurationAction)
 {
     // Little hack here to get dependencies when HttpContext is not available
     if (HttpContext.Current != null)
         return LifetimeScope ?? (LifetimeScope = InitializeLifetimeScope(configurationAction, container));
     return InitializeLifetimeScope(configurationAction, container);
 }
Ejemplo n.º 4
0
        /// <summary>
        /// Creates a new child scope or returns an existing child scope.
        /// </summary>
        /// <param name="parentScope">The current parent container.</param>
        /// <param name="scopeKindTag">
        /// A tag to identify this kind of scope so it can be reused to share objects 
        /// through fancy registration extensions (e.g. InstancePerSPSite, InstancePerSPWeb)
        /// </param>
        /// <param name="childScopeKey">A key to uniquely identify this scope within the container.</param>
        /// <returns>The child scope for the uniquely identified resource</returns>
        public ILifetimeScope GetChildLifetimeScope(ILifetimeScope parentScope, string scopeKindTag, string childScopeKey)
        {
            ILifetimeScope ensuredScope = null;

            // Don't bother locking if the instance is already created
            if (this.childScopes.ContainsKey(childScopeKey))
            {
                // Return the already-initialized container right away
                ensuredScope = this.childScopes[childScopeKey];
            }
            else
            {
                // Only one scope should be registered at a time in this helper instance, to be on the safe side
                lock (this.childScopesLockObject)
                {
                    // Just in case, check again (because the assignment could have happened before we took hold of lock)
                    if (this.childScopes.ContainsKey(childScopeKey))
                    {
                        ensuredScope = this.childScopes[childScopeKey];
                    }
                    else
                    {
                        // This scope will never be disposed, i.e. it will live as long as the parent
                        // container, provided no one calls Dispose on it.
                        // The newly created scope is meant to sandbox InstancePerLifetimeScope-registered objects
                        // so that they get shared only within a boundary uniquely identified by the key.
                        ensuredScope = parentScope.BeginLifetimeScope(scopeKindTag);
                        this.childScopes[childScopeKey] = ensuredScope;
                    }
                }
            }

            return ensuredScope;
        }
Ejemplo n.º 5
0
 //-----------------------------------------------------------------------------------------------------------------------------------------------------
 public WebApplicationComponent(IWebAppEndpoint endpoint, Auto<ILogger> logger, IComponentContext componentContext)
 {
     _app = endpoint.Contract;
     _address = endpoint.Address;
     _logger = logger.Instance;
     _container = (ILifetimeScope)componentContext;
 }
        protected override void ApplicationStartup(ILifetimeScope container, IPipelines pipelines)
        {
            pipelines.EnableJsonErrorResponse(container.Resolve<IErrorMapper>());
            pipelines.EnableCORS();

            base.ApplicationStartup(container, pipelines);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="AutofacDependencyResolver" /> class.
        /// </summary>
        /// <param name="lifetimeScope">The lifetime scope that services will be resolved from.</param>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown if <paramref name="lifetimeScope" /> is <see langword="null" />.
        /// </exception>
        public AutofacDependencyResolver(ILifetimeScope lifetimeScope) {
            if (lifetimeScope == null)
                throw new ArgumentNullException("lifetimeScope");

            _lifetimeScope = lifetimeScope;
            _lifetimeScope.ComponentRegistry.AddRegistrationSource(this);
        }
Ejemplo n.º 8
0
 // The bootstrapper enables you to reconfigure the composition of the framework,
 // by overriding the various methods and properties.
 // For more information https://github.com/NancyFx/Nancy/wiki/Bootstrapper
 //protected override void ApplicationStartup(ILifetimeScope container, IPipelines pipelines)
 //{
 //    // No registrations should be performed in here, however you may
 //    // resolve things that are needed during application startup.
 //}
 //protected override void ConfigureApplicationContainer(ILifetimeScope existingContainer)
 //{
 //    // Perform registration that should have an application lifetime
 //}
 protected override void ConfigureRequestContainer(ILifetimeScope container, NancyContext context)
 {
     // Perform registrations that should have a request lifetime
     var builder = new ContainerBuilder();
     builder.RegisterModule(new ServicesModule());
     builder.Update(container.ComponentRegistry);
 }
Ejemplo n.º 9
0
		public FilterPage ()
		{
			this.Icon = "slideout.png";
			this.Title = "Filter";

			_scope = App.AutoFacContainer.BeginLifetimeScope();

			var vm = _scope.Resolve<FilterViewModel> ();

			BindingContext = vm;

			var layout = new StackLayout ();

			layout.Children.Add (new Label() {Text = "Enter a filter"});
			layout.Children.Add (new Label() {Text = "Subject"});
			var subjectEntry = new Entry();
			subjectEntry.SetBinding (Entry.TextProperty, "Subject");
			layout.Children.Add (subjectEntry);
			var button = new Button () { Text = "Apply Filter" };
			button.SetBinding (Button.CommandProperty, "FilterMeasures");
			layout.Children.Add (button);

			Content = layout;


		}
 public AutofacMediatorBuilder(ILifetimeScope container)
 {
     _key = HandlerKey;
     _asyncKey = AsyncHandlerKey;
     _container = container;
     _builder = new ContainerBuilder();
 }
Ejemplo n.º 11
0
        protected override void ApplicationStartup(ILifetimeScope container, IPipelines pipelines)
        {
            pipelines.OnError.AddItemToEndOfPipeline((context, exception) =>
                                                         {
                                                             var message = string.Format("Exception: {0}", exception);
                                                             new ElmahErrorHandler.LogEvent(message).Raise();
                                                             return null;
                                                         });

            pipelines.BeforeRequest.AddItemToEndOfPipeline(ctx =>
                                                               {
                                                                   var lang = ctx.Request.Headers.AcceptLanguage.FirstOrDefault();
                                                                   if (lang != null)
                                                                   {
                                                                       // Accepted language can be something like "fi-FI", but it can also can be like fi-FI,fi;q=0.9,en;q=0.8
                                                                       if (lang.Contains(","))
                                                                           lang = lang.Substring(0, lang.IndexOf(","));

                                                                       System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo(lang);
                                                                       System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo(lang);
                                                                   }
                                                                   return null;
                                                               });

            DoMigrations();
        }
 public DatabaseLock(
     ILifetimeScope lifetimeScope,
     IClock clock)
 {
     _lifetimeScope = lifetimeScope;
     _clock = clock;
 }
Ejemplo n.º 13
0
        protected override void ApplicationStartup(ILifetimeScope container, IPipelines pipelines)
        {
            base.ApplicationStartup(container, pipelines);

            // register interfaces/implementations
            container.Update(builder => builder
                //.RegisterType<CouchDbTShirtRepository>()
                .RegisterType<MockedTShirtRepository>()
                .As<ITShirtRepository>());

            // register MyCouchStore parameter for couchdb repo classes
            container.Update(builder => builder
                .RegisterType<MyCouchStore>()
                .As<IMyCouchStore>()
                .UsingConstructor(typeof (string), typeof (string))
                .WithParameters(new [] {
                    new NamedParameter("dbUri","http://*****:*****@localhost:5984/"),
                    new NamedParameter("dbName","cshirts")
                })
            );

            // TODO: remove after implementing REST-Api & replacing razor with angular
            // display razor error messages
            StaticConfiguration.DisableErrorTraces = false;
        }
Ejemplo n.º 14
0
        protected override void ConfigureApplicationContainer(ILifetimeScope container)
        {
            base.ConfigureApplicationContainer(container);

            var builder = new ContainerBuilder();

            builder.RegisterType<AppSettings>().As<IAppSettings>().SingleInstance();
            builder.RegisterType<DummyMailChimpWebhooks>().As<IMailChimpWebhooks>().SingleInstance();
            builder.RegisterType<DummyMailgunWebhooks>().As<IMailgunWebhooks>().SingleInstance();
            builder.RegisterType<AzureTableStorageTodoService>().As<ITodoService>().SingleInstance();

            // Consumers and sagas
            builder.RegisterAssemblyTypes(typeof(Bootstrapper).Assembly)
                .Where(t => t.Implements<ISaga>() ||
                            t.Implements<IConsumer>())
                .AsSelf();

            // Saga repositories
            builder.RegisterGeneric(typeof(InMemorySagaRepository<>))
                .As(typeof(ISagaRepository<>))
                .SingleInstance();

            // Service bus
            builder.Register(c => ServiceBusFactory.New(sbc =>
            {
                sbc.ReceiveFrom("loopback://localhost/queue");
                sbc.Subscribe(x => x.LoadFrom(container));
            })).As<IServiceBus>().SingleInstance();

            builder.Update(container.ComponentRegistry);
        }
        /// <summary>
        /// 初始化一个 <see cref="AutofacLifetimeScopeProvider"/> 类的实例.
        /// </summary>
        /// <param name="container">
        /// 容器.
        /// </param>
        public AutofacLifetimeScopeProvider(ILifetimeScope container)
        {
            Guard.ArgumentNotNull(() => container);

            this.container = container;
            AutofacRequestLifetimeHttpModule.SetLifetimeScopeProvider(this);
        }
 protected MessagePipelineBase(IMessageHandlerProvider messageHandlerProvider, ILifetimeScope lifetimeScope, IMessage message, Logger logger)
     : base(logger)
 {
     _messageHandlerProvider = messageHandlerProvider;
     LifetimeScope = lifetimeScope;
     Message = message;
 }
Ejemplo n.º 17
0
        protected override void ApplicationStartup(ILifetimeScope container, IPipelines pipelines)
        {
            pipelines.OnError.AddItemToEndOfPipeline(LogException);
            pipelines.BeforeRequest.AddItemToEndOfPipeline(DetectLanguage);

            DoMigrations();
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="AutofacWebApiDependencyResolver"/> class.
        /// </summary>
        /// <param name="container">The container that nested lifetime scopes will be create from.</param>
        public AutofacWebApiDependencyResolver(ILifetimeScope container)
        {
            if (container == null) throw new ArgumentNullException("container");

            _container = container;
            _rootDependencyScope = new AutofacWebApiDependencyScope(container);
        }
Ejemplo n.º 19
0
        protected override void ApplicationStartup(ILifetimeScope container, IPipelines pipelines)
        {
            StaticConfiguration.DisableErrorTraces = false;

              // Enable memory sessions, and secure them against session hijacking
              pipelines.EnableInProcSessions();
              pipelines.BeforeRequest.AddItemToStartOfPipeline(ctx => {
            var antiSessionHijackLogic = container.Resolve<IAntiSessionHijackLogic>();
            return antiSessionHijackLogic.InterceptHijackedSession(ctx.Request);
              });
              pipelines.AfterRequest.AddItemToEndOfPipeline(ctx => {
            var antiSessionHijackLogic = container.Resolve<IAntiSessionHijackLogic>();
            antiSessionHijackLogic.ProtectResponseFromSessionHijacking(ctx);
              });

              // Load the user from the AspNet session. If one is found, create a Nancy identity and assign it.
              pipelines.BeforeRequest.AddItemToEndOfPipeline(ctx => {
            var identityAssigner = container.Resolve<INancyIdentityFromContextAssigner>();
            identityAssigner.AssignNancyIdentityFromContext(ctx);
            return null;
              });

              pipelines.OnError = pipelines.OnError
            + ErrorPipelines.HandleModelBindingException()
            + ErrorPipelines.HandleRequestValidationException()
            + ErrorPipelines.HandleSecurityException();

              base.ApplicationStartup(container, pipelines);
        }
Ejemplo n.º 20
0
 public void KillEmAll()
 {
     Scope.KillEmAll();
     if (AfScope.IsInstance())
         AfScope.Dispose();
     AfScope = Container.BeginLifetimeScope();
 }
Ejemplo n.º 21
0
        protected override void Resolve(ILifetimeScope container) {
            _compositionStrategy = container.Resolve<CompositionStrategy>();
            _compositionStrategy.Logger = container.Resolve<ILogger>();

            var alphaExtension = new ExtensionDescriptor {
                Id = "Alpha",
                Name = "Alpha",
                ExtensionType = "Module"
            };

            var alphaFeatureDescriptor = new FeatureDescriptor {
                Id = "Alpha",
                Name = "Alpha",
                Extension = alphaExtension
            };

            var betaFeatureDescriptor = new FeatureDescriptor {
                Id = "Beta",
                Name = "Beta",
                Extension = alphaExtension,
                Dependencies = new List<string> {
                    "Alpha"
                }
            };

            alphaExtension.Features = new List<FeatureDescriptor> {
                alphaFeatureDescriptor,
                betaFeatureDescriptor
            };

            _availableExtensions = new[] {
                alphaExtension
            };

            _installedFeatures = new List<Feature> {
                new Feature {
                    Descriptor = alphaFeatureDescriptor,
                    ExportedTypes = new List<Type> {
                        typeof(AlphaDependency)
                    }
                },
                new Feature {
                    Descriptor = betaFeatureDescriptor,
                    ExportedTypes = new List<Type> {
                        typeof(BetaDependency)
                    }
                }
            };

            _loggerMock.Setup(x => x.IsEnabled(It.IsAny<LogLevel>())).Returns(true);

            _extensionManager.Setup(x => x.AvailableExtensions()).Returns(() => _availableExtensions);

            _extensionManager.Setup(x => x.AvailableFeatures()).Returns(() =>
                _extensionManager.Object.AvailableExtensions()
                .SelectMany(ext => ext.Features)
                .ToReadOnlyCollection());

            _extensionManager.Setup(x => x.LoadFeatures(It.IsAny<IEnumerable<FeatureDescriptor>>())).Returns(() => _installedFeatures);
        }
Ejemplo n.º 22
0
        public static HttpConfiguration Configure(IdentityServerOptions options, ILifetimeScope container)
        {
            var config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();
            config.SuppressDefaultHostAuthentication();

            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            config.Services.Add(typeof(IExceptionLogger), new LogProviderExceptionLogger());
            config.Services.Replace(typeof(IHttpControllerTypeResolver), new HttpControllerTypeResolver());
            config.Formatters.Remove(config.Formatters.XmlFormatter);

            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.LocalOnly;

            if (options.LoggingOptions.EnableWebApiDiagnostics)
            {
                var liblog = new TraceSource("LibLog");
                liblog.Switch.Level = SourceLevels.All;
                liblog.Listeners.Add(new LibLogTraceListener());

                var diag = config.EnableSystemDiagnosticsTracing();
                diag.IsVerbose = options.LoggingOptions.WebApiDiagnosticsIsVerbose;
                diag.TraceSource = liblog;
            }

            ConfigureRoutes(options, config);

            return config;
        }
 /// <summary>
 ///     Initializes a new instance of the <see cref="AutofacJobFactory" /> class.
 /// </summary>
 /// <param name="lifetimeScope">The lifetime scope.</param>
 /// <param name="scopeName">Name of the scope.</param>
 public AutofacJobFactory(ILifetimeScope lifetimeScope, string scopeName)
 {
     if (lifetimeScope == null) throw new ArgumentNullException("lifetimeScope");
     if (scopeName == null) throw new ArgumentNullException("scopeName");
     _lifetimeScope = lifetimeScope;
     _scopeName = scopeName;
 }
        protected override void RequestStartup(ILifetimeScope container, IPipelines pipelines, NancyContext context)
        {
            // No registrations should be performed in here, however you may
            // resolve things that are needed during request startup.

            FormsAuthentication.Enable(pipelines, new FormsAuthenticationConfiguration()
            {
                RedirectUrl = "~/account/login",
                UserMapper = container.Resolve<IUserMapper>(),
            });

            pipelines.BeforeRequest.AddItemToEndOfPipeline(c =>
            {
                if (c.CurrentUser.IsAuthenticated())
                {
                    container.Resolve<ITenantContext>().SetTenantId(c.CurrentUser.AsAuthenticatedUser().Id, c.CurrentUser.HasClaim("Admin"));
                    c.ViewBag.UserName = c.CurrentUser.AsAuthenticatedUser().FullName;
                    c.ViewBag.IsAdmin = c.CurrentUser.HasClaim("Admin");
                }
                else
                    container.Resolve<ITenantContext>().SetTenantId(null, false);

                return null;
            });
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AutofacDependencyResolver" /> class.
        /// </summary>
        /// <param name="lifetimeScope">The lifetime scope that services will be resolved from.</param>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown if <paramref name="lifetimeScope" /> is <see langword="null" />.
        /// </exception>
        public AutofacDependencyResolver(ILifetimeScope lifetimeScope)
        {
            if (lifetimeScope == null)
                throw new ArgumentNullException("lifetimeScope");

            _lifetimeScope = lifetimeScope;
        }
Ejemplo n.º 26
0
 public PluginHttpApi(
     ILogger logger,
     ILifetimeScope lifetimeScope)
 {
     _logger = logger;
     _lifetimeScope = lifetimeScope;
 }
        protected override void ConfigureApplicationContainer(ILifetimeScope existingContainer)
        {
            var setup = new Setup((IContainer)existingContainer);

            // defaults
            setup.WithGuidGenerator();
            setup.WithThreadStaticTenantContext();
            setup.WithMongo("MongoConnectionReadModel");
            setup.RegisterReadModelRepositories();

            // web specific
            var builder = new ContainerBuilder();
            builder.RegisterType<NancyUserMapper>().As<IUserMapper>();
            builder.RegisterType<StaticContentResolverForInMemory>().As<IStaticContentResolver>();
            builder.RegisterType<ExcelService>().As<IExcelService>();
            builder.Update(setup.Container.ComponentRegistry);

            // bus
            setup.WithInMemoryBus();
            setup.RegisterReadModelHandlers();

            // eventstore
            setup.WithMongoEventStore("MongoConnectionEventStore",
                new AuthorizationPipelineHook(setup.Container),
                new MessageDispatcher(setup.Container),
                false);

            // start the bus
            setup.Container.Resolve<IServiceBus>().Start(ConfigurationManager.AppSettings["serviceBusEndpoint"]);
        }
Ejemplo n.º 28
0
 public Rebuild(IStoreEvents eventStore, IDomainUpdateServiceBusHandlerHook hook, ILifetimeScope container, IMongoContext mongo)
 {
     _eventStore = eventStore;
     _hook = hook;
     _container = container;
     _mongo = mongo;
 }
Ejemplo n.º 29
0
        public static void Initialize()
        {
            /*bool databaseInstalled = DataSettingsHelper.DatabaseIsInstalled();
            if (databaseInstalled)
            {
                //startup tasks
                RunStartupTasks();
            }*/
            //startup tasks
            //RunStartupTasks();

            var builder = new ContainerBuilder();
            builder.RegisterType<WebAppTypeFinder>().As<ITypeFinder>().SingleInstance();
               _container =  builder.Build();
            if (HttpContext.Current == null)
            {
                _applicationContainer = new StubLifetimeScopeProvider(_container).GetLifetimeScope(null);
            }
            else
            {
                _applicationContainer = _container;
            }
            var typeFinder =  _container.Resolve<ITypeFinder>();
            UpdateContainer(x =>
            {
                var drTypes = typeFinder.FindClassesOfType<IDependencyRegistrar>();
                var drInstances = new List<IDependencyRegistrar>();
                foreach (var drType in drTypes)
                    drInstances.Add((IDependencyRegistrar)Activator.CreateInstance(drType));
                //sort
                drInstances = drInstances.AsQueryable().OrderBy(t => t.Order).ToList();
                foreach (var dependencyRegistrar in drInstances)
                    dependencyRegistrar.Register(x, typeFinder);
            });
        }
Ejemplo n.º 30
0
 protected override void ConfigureApplicationContainer(ILifetimeScope existingContainer)
 {
     var builder = new ContainerBuilder();
     _tasks.ForEach(task => task.Task.Invoke(builder));
     builder.Update(existingContainer.ComponentRegistry);
     base.ConfigureApplicationContainer(existingContainer);
 }
 public void DisposeJobLifetimeScope()
 {
     _childLifetimeScope.Dispose();
     _childLifetimeScope = null;
 }
Ejemplo n.º 32
0
 public FactoryAbstract(ILifetimeScope scope)
 {
     _scope = scope;
 }
Ejemplo n.º 33
0
 public void Run(ILifetimeScope scope)
 {
 }
Ejemplo n.º 34
0
 public void UseContainer(ILifetimeScope lifetimeScope)
 {
     SetContainer(lifetimeScope);
 }
Ejemplo n.º 35
0
 public SettingsWindow(SettingsWidgetModel viewModel, ILifetimeScope container) : base(container)
 {
     InitializeComponent();
     DataContext = viewModel;
 }
Ejemplo n.º 36
0
 public AsyncRunner(ILifetimeScope lifetimeScope)
 {
     LifetimeScope = lifetimeScope;
 }
Ejemplo n.º 37
0
 public QueryExecutor(ILifetimeScope lifetimeScope)
 {
     _lifetimeScope = lifetimeScope;
 }
Ejemplo n.º 38
0
 public static ILifetimeScope SetScopeValue <T>(this ILifetimeScope scope, T instance)
 {
     return(SetScopeFactory(scope, () => instance));
 }
Ejemplo n.º 39
0
 public AutofacTypeResolver(ILifetimeScope scope)
 {
     _scope = scope;
 }
 public void CreateJobLifetimeScope()
 {
     _childLifetimeScope = _mainContainer.BeginLifetimeScope();
 }
Ejemplo n.º 41
0
 public LineHandlerFactory(ILifetimeScope lifetimeScope)
 {
     this.lifetimeScope = lifetimeScope;
 }
Ejemplo n.º 42
0
 public static ILifetimeScope SetScopeFactory <T>(this ILifetimeScope scope, Func <T> factory)
 {
     ScopeMapFor(scope)[typeof(T)] = factory;
     return(scope);
 }
Ejemplo n.º 43
0
        public bool Start(HostControl hostControl)
        {
            _log.InfoFormat($"Starting {GetType().GetDisplayName()}");

            var started = new List <ServiceControl>();

            try
            {
                var scanner = new AssemblyScanner();

                List <AssemblyRegistration> registrations = scanner.GetAssemblyRegistrations().ToList();

                _log.Info($"Found {registrations.Count} assembly registrations");
                foreach (var registration in registrations)
                {
                    _log.Info($"Assembly: {registration.Assembly.GetName().Name}");
                    foreach (var type in registration.Types)
                    {
                        _log.Info($"  Type: {type.GetTypeName()}");
                    }
                }

                var busFactoryType = scanner.GetHostBusFactoryType();
                if (busFactoryType == null)
                {
                    throw new ConfigurationException("A valid transport assembly was not found.");
                }

                _bootstrapperScope = CreateBootstrapperScope(registrations, busFactoryType);

                var bootstrappers = _bootstrapperScope.Resolve <IEnumerable <IServiceBootstrapper> >();

                List <ServiceControl> services = bootstrappers.Select(x => x.CreateService()).ToList();

                Parallel.ForEach(services, serviceControl =>
                {
                    hostControl.RequestAdditionalTime(TimeSpan.FromMinutes(1));

                    StartService(hostControl, serviceControl);

                    lock (started)
                    {
                        started.Add(serviceControl);
                    }
                });

                _services.AddRange(started);

                return(true);
            }
            catch (Exception ex)
            {
                _log.Error("Service failed to start", ex);

                Parallel.ForEach(started, service =>
                {
                    hostControl.RequestAdditionalTime(TimeSpan.FromMinutes(1));
                    StopService(hostControl, service);
                });

                throw;
            }
        }
Ejemplo n.º 44
0
 public ShellViewModel(IEventAggregator eventAggregator, ChocolateyInstaller chocolateyInstaller, LicenseAgreement licenseAgreement, ILifetimeScope lifetimeScope, PowerShellRunner powerShellRunner)
 {
     this.chocolateyInstaller = chocolateyInstaller;
     this.licenseAgreement    = licenseAgreement;
     this.lifetimeScope       = lifetimeScope;
     this.powerShellRunner    = powerShellRunner;
     this.eventAggregator     = eventAggregator;
     RunStartupSequence();
 }
Ejemplo n.º 45
0
 public AutofacContainer(ILifetimeScope container)
 {
     _container = container ?? new ContainerBuilder().Build();
 }
Ejemplo n.º 46
0
 public FDServiceHelper(ILifetimeScope lifetimeScope, ILogger <FDServiceHelper> logger)
 {
     _ApplicationContainer = lifetimeScope;
     _Logger = logger;
 }
Ejemplo n.º 47
0
 public LifetimeScopeEndingEventArgs(ILifetimeScope lifetimeScope)
 {
     this._lifetimeScope = lifetimeScope;
 }
Ejemplo n.º 48
0
 public MassTransitHostService(ILifetimeScope hostScope)
 {
     _hostScope = hostScope;
     _services  = new List <ServiceControl>();
 }
Ejemplo n.º 49
0
 AutofacResolver(ILifetimeScope container)
 {
     _container = container ?? throw new ArgumentNullException("container");
 }
Ejemplo n.º 50
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AutoFacServiceLocatorProvider"/> class.
        /// </summary>
        /// <param name="container">
        /// The container.
        /// </param>
        public AutoFacServiceLocatorProvider([NotNull] ILifetimeScope container)
        {
            CodeContracts.VerifyNotNull(container, "container");

            this.Container = container;
        }
Ejemplo n.º 51
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="AutofacJobFactory" /> class.
 /// </summary>
 /// <param name="lifetimeScope">The lifetime scope.</param>
 /// <param name="scopeTag">The tag to use for new scopes.</param>
 /// <exception cref="ArgumentNullException">
 ///     <paramref name="lifetimeScope" /> or <paramref name="scopeTag" /> is
 ///     <see langword="null" />.
 /// </exception>
 public AutofacJobFactory([NotNull] ILifetimeScope lifetimeScope, [NotNull] object scopeTag)
 {
     _lifetimeScope = lifetimeScope ?? throw new ArgumentNullException(nameof(lifetimeScope));
     _scopeTag      = scopeTag ?? throw new ArgumentNullException(nameof(scopeTag));
 }
Ejemplo n.º 52
0
 public AutofacJobFactory(ILifetimeScope scope) => this.scope = scope;
Ejemplo n.º 53
0
        /// <summary>
        /// Overridable resolve strategy for IJob instance
        /// </summary>
        /// <param name="nestedScope">
        ///     Nested ILifetimeScope for resolving Job instance with other dependencies
        /// </param>
        /// <param name="jobDetail">
        ///     The <see cref="T:Quartz.IJobDetail" />
        ///     and other info about job
        /// </param>
        /// <returns></returns>
        protected virtual IJob ResolveJobInstance(ILifetimeScope nestedScope, IJobDetail jobDetail)
        {
            var jobType = jobDetail.JobType;

            return((IJob)nestedScope.Resolve(jobType));
        }
Ejemplo n.º 54
0
 public override void Finish()
 {
     _container = _builder.Build();
 }
Ejemplo n.º 55
0
 public virtual void BeforeEachTest()
 {
     Scope = Container.BeginLifetimeScope();
 }
Ejemplo n.º 56
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="T:System.Object" /> class.
 /// </summary>
 public JobTrackingInfo(ILifetimeScope scope)
 {
     Scope = scope;
 }
 public DummyClass(IObjectRegistration p1, ContainerOption p2, ILifetimeScope p3)
 {
 }
Ejemplo n.º 58
0
 public MessageProcessor(ILifetimeScope lifetimeScope)
 {
     _lifetimeScope = lifetimeScope;
 }
Ejemplo n.º 59
0
 public clsTaller(ILifetimeScope lifetimeScope) : base(lifetimeScope)
 {
 }
 public MetricsQueryDataContextFactory(ILifetimeScope lifetimeScope)
 {
     this.lifetimeScope = lifetimeScope ?? throw new ArgumentNullException(nameof(lifetimeScope));
 }