public PingHub(ILifetimeScope lifetimeScope) { // Create a lifetime scope for this hub instance. _hubLifetimeScope = lifetimeScope.BeginLifetimeScope(); // Resolve the dependencies from the hub lifetime scope (unfortunately, service locator style). _bar = _hubLifetimeScope.Resolve<IBar>(); _foo = _hubLifetimeScope.Resolve<IFoo>(); }
public NotificationHub(ILifetimeScope scope) : base() { var lifetimeScope = scope.BeginLifetimeScope("AutofacWebRequest"); this.gameService = lifetimeScope.Resolve<IGameService>(); this.unitOfWork = lifetimeScope.Resolve<IUnitOfWork>(); this.userManager = lifetimeScope.Resolve<UserManager<User>>(); }
private static void SimulateRequest(ILifetimeScope rootLifetimeScope) { using (var requestLifetimeScope = rootLifetimeScope.BeginLifetimeScope()) { var consumer = requestLifetimeScope.Resolve<ServiceConsumer>(); Console.WriteLine(consumer.DoSomething()); } }
public CommonHub(ILifetimeScope lifetimeScope) { // Create a lifetime scope for the hub. _hubLifetimeScope = lifetimeScope.BeginLifetimeScope(); // Resolve dependencies from the hub lifetime scope _documentService = _hubLifetimeScope.Resolve<IDocumentsService>(); // singleton _tableService = _hubLifetimeScope.Resolve<ITableService>(); // singleton _counterService = _hubLifetimeScope.Resolve<IDistributedCounter>(); // singleton }
static ILifetimeScope InitializeLifetimeScope(Action<ContainerBuilder> configurationAction, ILifetimeScope container) { return (configurationAction == null) ? container.BeginLifetimeScope(HttpRequestTag) //, mp => //{ // mp.RegisterHttpRequestMessage(GlobalConfiguration.Configuration); // // mp.Update(container.ComponentRegistry); //}) : container.BeginLifetimeScope(HttpRequestTag, configurationAction); }
public static IAppBuilder UseAutofacMiddleware(this IAppBuilder app, ILifetimeScope container) { app.Use(async (context, next) => { using (var lifetimeScope = container.BeginLifetimeScope(Constants.LifetimeScopeTag, b => b.RegisterInstance(context).As<IOwinContext>())) { context.Set(Constants.OwinLifetimeScopeKey, lifetimeScope); await next(); } }); return UseMiddlewareFromContainer(app, container); }
private static void DispatchCommit(ILifetimeScope container, Commit commit) { using (var scope = container.BeginLifetimeScope()) { NanoMessageBus.IPublishMessages publisher = scope.Resolve<NanoMessageBus.IPublishMessages>(); publisher.Publish(commit.Events.Select(e => e.Body).ToArray()); // need to complete and dispose the uow to do the actual publishing since // the IHandleUnitOfWork is registered as ExternalyOwned using (IHandleUnitOfWork uow = scope.Resolve<IHandleUnitOfWork>()) { uow.Complete(); } } }
private static void DispatchCommit(ILifetimeScope container, Commit commit) { // TODO: the process might crash after the commit has been writen to the eventstore // but before we have a chance to publish the messages to the bus. using (var scope = container.BeginLifetimeScope()) { NanoMessageBus.IPublishMessages publisher = scope.Resolve<NanoMessageBus.IPublishMessages>(); publisher.Publish(commit.Events.Select(e => e.Body).ToArray()); // need to complete and dispose the uow to do the actual publishing since // the IHandleUnitOfWork is registered as ExternalyOwned using (IHandleUnitOfWork uow = scope.Resolve<IHandleUnitOfWork>()) { uow.Complete(); } } }
public static IAppBuilder UseAutofacMiddleware(this IAppBuilder app, ILifetimeScope container) { if (app == null) throw new ArgumentNullException("app"); if (app.Properties.ContainsKey(MiddlewareRegisteredKey)) return app; app.Use(async (context, next) => { using (var lifetimeScope = container.BeginLifetimeScope(Constants.LifetimeScopeTag, b => b.RegisterInstance(context).As<IOwinContext>())) { context.Set(Constants.OwinLifetimeScopeKey, lifetimeScope); await next(); } }); UseMiddlewareFromContainer(app, container); app.Properties.Add(MiddlewareRegisteredKey, true); return app; }
/// <summary> /// Создать область видимости приложения /// </summary> /// <param name="container">Контейнер области видимости приложения</param> public AppCore(ILifetimeScope container) : base() { _rootScope = container; Scope = _rootScope.BeginLifetimeScope(b => { b.RegisterType<Config>() .AsSelf() .SingleInstance(); b.RegisterInstance(this) .AsSelf() .SingleInstance(); b.Register(c => this.BeginScope()) .As<IAppScope>() .AsSelf(); b.RegisterModule<EmitImplementerModule>(); }); Instance = this; }
public static IAppBuilder UseAutofacMiddleware(this IAppBuilder app, ILifetimeScope container) { if (app == null) throw new ArgumentNullException("app"); // idsvr : remove these guards so that multiple copies of middleware can be registered //if (app.Properties.ContainsKey(MiddlewareRegisteredKey)) return app; app.Use(async (context, next) => { using (var lifetimeScope = container.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag, b => b.RegisterInstance(context).As<IOwinContext>())) { context.Set(Constants.OwinLifetimeScopeKey, lifetimeScope); await next(); } }); UseMiddlewareFromContainer(app, container); // idsvr : remove these guards so that multiple copies of middleware can be registered //app.Properties.Add(MiddlewareRegisteredKey, true); return app; }
public IDependencyScope BeginScope() { ILifetimeScope lifetimeScope = _container.BeginLifetimeScope(); return(new AutofacWebApiDependencyScope(lifetimeScope)); }
public virtual async Task <InstallationResult> InstallAsync(InstallationModel model, ILifetimeScope scope, CancellationToken cancelToken = default) { Guard.NotNull(model, nameof(model)); UpdateResult(x => { x.ProgressMessage = GetResource("Progress.CheckingRequirements"); x.Completed = false; Logger.Info(x.ProgressMessage); }); if (DataSettings.DatabaseIsInstalled()) { return(UpdateResult(x => { x.Success = true; x.RedirectUrl = _urlHelper.Action("Index", "Home"); Logger.Info("Application already installed"); })); } DbFactory dbFactory = null; try { dbFactory = DbFactory.Load(model.DataProvider, _appContext.TypeScanner); } catch (Exception ex) { return(UpdateResult(x => { x.Errors.Add(ex.Message); Logger.Error(ex); })); } model.DbRawConnectionString = model.DbRawConnectionString?.Trim(); DbConnectionStringBuilder conStringBuilder = null; try { // Try to create connection string if (model.UseRawConnectionString) { conStringBuilder = dbFactory.CreateConnectionStringBuilder(model.DbRawConnectionString); } else { // Structural connection string var userId = model.DbUserId; var password = model.DbPassword; if (model.DataProvider == "sqlserver" && model.DbAuthType == "windows") { userId = null; password = null; } conStringBuilder = dbFactory.CreateConnectionStringBuilder(model.DbServer, model.DbName, userId, password); } } catch (Exception ex) { return(UpdateResult(x => { x.Errors.Add(GetResource("ConnectionStringWrongFormat")); Logger.Error(ex, x.Errors.Last()); })); } // Check FS access rights CheckFileSystemAccessRights(GetInstallResult().Errors); if (GetInstallResult().HasErrors) { return(UpdateResult(x => { x.Completed = true; x.Success = false; x.RedirectUrl = null; Logger.Error("Aborting installation."); })); } ILifetimeScope richScope = null; SmartDbContext dbContext = null; var shouldDeleteDbOnFailure = false; try { cancelToken.ThrowIfCancellationRequested(); var conString = conStringBuilder.ConnectionString; var settings = DataSettings.Instance; settings.AppVersion = SmartstoreVersion.Version; settings.DbFactory = dbFactory; settings.ConnectionString = conString; // So that DataSettings.DatabaseIsInstalled() returns false during installation. DataSettings.SetTestMode(true); // Resolve SeedData instance from primary language var lazyLanguage = GetAppLanguage(model.PrimaryLanguage); if (lazyLanguage == null) { return(UpdateResult(x => { x.Errors.Add(GetResource("Install.LanguageNotRegistered").FormatInvariant(model.PrimaryLanguage)); x.Completed = true; x.Success = false; x.RedirectUrl = null; Logger.Error(x.Errors.Last()); })); } // Create the DataContext dbContext = (SmartDbContext)dbFactory.CreateApplicationDbContext( conString, _appContext.AppConfiguration.DbMigrationCommandTimeout, SmartDbContext.MigrationHistoryTableName); // Delete only on failure if WE created the database. var canConnectDatabase = await dbContext.Database.CanConnectAsync(cancelToken); shouldDeleteDbOnFailure = !canConnectDatabase; cancelToken.ThrowIfCancellationRequested(); // Create Language domain object from lazyLanguage var languages = dbContext.Languages; var primaryLanguage = new Language { Name = lazyLanguage.Metadata.Name, LanguageCulture = lazyLanguage.Metadata.Culture, UniqueSeoCode = lazyLanguage.Metadata.UniqueSeoCode, FlagImageFileName = lazyLanguage.Metadata.FlagImageFileName }; // Build the seed configuration model var seedConfiguration = new SeedDataConfiguration { DefaultUserName = model.AdminEmail, DefaultUserPassword = model.AdminPassword, SeedSampleData = model.InstallSampleData, Data = lazyLanguage.Value, Language = primaryLanguage, StoreMediaInDB = model.MediaStorage == "db", ProgressMessageCallback = msg => UpdateResult(x => x.ProgressMessage = GetResource(msg)) }; var seeder = new InstallationDataSeeder(seedConfiguration, Logger, _httpContextAccessor); UpdateResult(x => { x.ProgressMessage = GetResource("Progress.BuildingDatabase"); Logger.Info(x.ProgressMessage); }); //// TEST //return UpdateResult(x => //{ // x.Completed = true; // x.Success = true; // //x.RedirectUrl = _urlHelper.Action("Index", "Home"); // Logger.Info("Installation completed successfully"); //}); // ===>>> Actually performs database creation. await dbContext.Database.MigrateAsync(cancelToken); cancelToken.ThrowIfCancellationRequested(); // ===>>> Seeds data. await seeder.SeedAsync(dbContext); cancelToken.ThrowIfCancellationRequested(); // ... Install modules // Detect media file tracks (must come after plugins installation) UpdateResult(x => { x.ProgressMessage = GetResource("Progress.ProcessingMedia"); Logger.Info(x.ProgressMessage); }); richScope = scope.BeginLifetimeScope(c => { // At this stage (after the database has been created and seeded completely) we can create a richer service scope // to minimize the risk of dependency resolution exceptions during more complex install operations. c.RegisterInstance(dbContext); c.Register <IStoreContext>(cc => new StoreContext(cc.Resolve <ICacheFactory>(), null, _httpContextAccessor, cc.Resolve <IActionContextAccessor>())); c.Register <ISettingFactory>(cc => new SettingFactory(cc.Resolve <ICacheManager>(), null, _httpContextAccessor)); }); var mediaTracker = richScope.Resolve <IMediaTracker>(); foreach (var album in richScope.Resolve <IAlbumRegistry>().GetAlbumNames(true)) { await mediaTracker.DetectAllTracksAsync(album, cancelToken); } cancelToken.ThrowIfCancellationRequested(); UpdateResult(x => { x.ProgressMessage = GetResource("Progress.Finalizing"); Logger.Info(x.ProgressMessage); }); // Now persist settings settings.Save(); // SUCCESS: Redirect to home page return(UpdateResult(x => { x.Completed = true; x.Success = true; x.RedirectUrl = _urlHelper.Action("Index", "Home"); Logger.Info("Installation completed successfully"); })); } catch (Exception ex) { Logger.Error(ex); // Delete Db if it was auto generated if (dbContext != null && shouldDeleteDbOnFailure) { try { Logger.Debug("Deleting database"); await dbContext.Database.EnsureDeletedAsync(cancelToken); } catch { } } // Clear provider settings if something got wrong DataSettings.Delete(); var msg = ex.Message; var realException = ex; while (realException.InnerException != null) { realException = realException.InnerException; } if (!object.Equals(ex, realException)) { msg += " (" + realException.Message + ")"; } return(UpdateResult(x => { x.Errors.Add(string.Format(GetResource("SetupFailed"), msg)); x.Success = false; x.Completed = true; x.RedirectUrl = null; })); } finally { if (dbContext != null) { dbContext.Dispose(); } if (richScope != null) { richScope.Dispose(); } } }
public AutofacFilterContextScope(TContext context, ILifetimeScope lifetimeScope) { Context = context; _lifetimeScope = context.TryGetPayload(out ILifetimeScope scope) ? new NoopLifetimeScope(scope) : lifetimeScope.BeginLifetimeScope(); }
/// <summary> /// For renewal and creating scheduled task /// </summary> /// <param name="target"></param> /// <param name="renewal"></param> /// <param name="runLevel"></param> /// <returns></returns> public ILifetimeScope Execution(ILifetimeScope target, Renewal renewal, RunLevel runLevel) { return target.BeginLifetimeScope(builder => { builder.Register(c => runLevel).As<RunLevel>(); builder.RegisterType<FindPrivateKey>().SingleInstance(); // Used to configure TaskScheduler without renewal if (renewal != null) { builder.RegisterInstance(renewal); builder.RegisterInstance(renewal.StorePluginOptions).As(renewal.StorePluginOptions.GetType()); if (renewal.CsrPluginOptions != null) { builder.RegisterInstance(renewal.CsrPluginOptions).As(renewal.CsrPluginOptions.GetType()); } if (renewal.OrderPluginOptions != null) { builder.RegisterInstance(renewal.OrderPluginOptions).As(renewal.OrderPluginOptions.GetType()); } builder.RegisterInstance(renewal.ValidationPluginOptions).As(renewal.ValidationPluginOptions.GetType()); builder.RegisterInstance(renewal.TargetPluginOptions).As(renewal.TargetPluginOptions.GetType()); // Find factory based on options builder.Register(x => { var plugin = x.Resolve<IPluginService>(); var match = plugin.GetFactories<IValidationPluginOptionsFactory>(target).First(vp => vp.OptionsType.PluginId() == renewal.ValidationPluginOptions.Plugin); if (match == null) { return new NullValidationFactory(); } return match; }).As<IValidationPluginOptionsFactory>().SingleInstance(); if (renewal.CsrPluginOptions != null) { builder.RegisterType(renewal.CsrPluginOptions.Instance).As<ICsrPlugin>().SingleInstance(); } if (renewal.OrderPluginOptions != null) { builder.RegisterType(renewal.OrderPluginOptions.Instance).As<IOrderPlugin>().SingleInstance(); } else { builder.RegisterType<Plugins.OrderPlugins.Single>().As<IOrderPlugin>().SingleInstance(); } builder.RegisterType(renewal.ValidationPluginOptions.Instance).As<IValidationPlugin>().SingleInstance(); builder.RegisterType(renewal.TargetPluginOptions.Instance).As<ITargetPlugin>().SingleInstance(); foreach (var i in renewal.InstallationPluginOptions) { builder.RegisterInstance(i).As(i.GetType()); } foreach (var i in renewal.StorePluginOptions) { builder.RegisterInstance(i).As(i.GetType()); } } }); }
static ILifetimeScope InitializeLifetimeScope(Action <ContainerBuilder> configurationAction, ILifetimeScope container) { return((configurationAction == null) ? container.BeginLifetimeScope(HttpRequestTag) : container.BeginLifetimeScope(HttpRequestTag, configurationAction)); }
public IDependencyScope BeginScope() { return(new AutofacDependencyResolver(scope.BeginLifetimeScope())); }
public static ILifetimeScope BeginLifetimeScope(ILifetimeScope scope, IMessageActivity message) { var inner = scope.BeginLifetimeScope(LifetimeScopeTag); inner.Resolve<IMessageActivity>(TypedParameter.From(message)); return inner; }
public Job(ILifetimeScope scope) { this.LifetimeScope = scope.BeginLifetimeScope("AutofacWebRequest"); }
public async Task StartConnecting(ILifetimeScope lifetimeScope) { var uris = new List <Uri>(); foreach (var serverUri in _options.ServerUris) { if (Uri.TryCreate(serverUri, UriKind.Absolute, out var uri)) { uris.Add(uri); } else { Logger.Warn("Unable to parse uri {uri}", serverUri); } } while (true) { foreach (var serverUri in uris) { Logger.Debug("Try to connect to {uri}", serverUri); try { var connection = await _serverConnector.TryConnect(serverUri); Logger.Debug("Connection succeeded, download modules"); await _moduleDownloader.Load(connection.PackagesLock, connection, CancellationToken.None); Logger.Debug("Modules downloaded successfully, loading configuration"); var configurationInfo = await ClientConfigurationResource.GetConfigurationsInfo(connection.RestClient); if (!_configurationManager.IsSynchronized(configurationInfo)) { var configurations = await ClientConfigurationResource.GetConfigurations(connection.RestClient); _configurationManager.Synchronize(configurations, connection.PackagesLock); } if (!_packageLockUpdater.Verify(connection.PackagesLock)) { _processController.Restart(); return; } var loadedContext = await _packageLockLoader.Load(connection.PackagesLock); var controllers = await loadedContext.GetControllers(); var restClientWrapper = lifetimeScope.Resolve <MazeRestClientWrapper>(); restClientWrapper.Initialize(connection.RestClient); CurrentConnectionScope = lifetimeScope.BeginLifetimeScope(builder => { if (loadedContext.PackagesLoaded) { loadedContext.Configure(builder); } builder.RegisterMazeServices(cache => cache.BuildCache(controllers)); }); CurrentConnection = connection; using (CurrentConnectionScope) { await CurrentConnectionScope.Execute <IConnectedAction>(); await connection.InitializeWebSocket(CurrentConnectionScope); } CurrentConnection = null; restClientWrapper.Initialize(null); break; } catch (Exception e) { Logger.Warn(e, "Error occurred when trying to connect to {uri}", serverUri); } } await Task.Delay(_options.ReconnectDelay); } }
/// <summary> /// 创建一个外壳容器。 /// </summary> /// <param name="settings">外壳设置。</param> /// <param name="blueprint">外壳蓝图。</param> /// <returns>外壳容器。</returns> public ILifetimeScope CreateContainer(ShellSettings settings, ShellBlueprint blueprint) { var intermediateScope = _lifetimeScope.BeginLifetimeScope( builder => { //TODO:CollectionOrderModule、CacheModule 等Module是公共的,需要验证 Root 范围注册了子级生命范围是否生效,如果生效则在外壳容器中忽略掉这些Module foreach (var item in blueprint.Dependencies.Where(t => typeof(IModule).IsAssignableFrom(t.Type))) { RegisterType(builder, item) .Keyed <IModule>(item.Type) .InstancePerDependency(); } }); return(intermediateScope.BeginLifetimeScope( "shell", builder => { builder.Register(ctx => settings); builder.Register(ctx => blueprint.Descriptor); builder.Register(ctx => blueprint); var moduleIndex = intermediateScope.Resolve <IIndex <Type, IModule> >(); foreach (var item in blueprint.Dependencies.Where(t => typeof(IModule).IsAssignableFrom(t.Type))) { builder.RegisterModule(moduleIndex[item.Type]); } foreach (var item in blueprint.Dependencies.Where(t => typeof(IDependency).IsAssignableFrom(t.Type))) { var registration = RegisterType(builder, item) .InstancePerLifetimeScope(); foreach (var interfaceType in item.Type.GetInterfaces() .Where(itf => typeof(IDependency).IsAssignableFrom(itf) && !typeof(IEventHandler).IsAssignableFrom(itf))) { registration = registration.As(interfaceType); if (typeof(ISingletonDependency).IsAssignableFrom(interfaceType)) { registration = registration.InstancePerMatchingLifetimeScope("shell"); } else if (typeof(IUnitOfWorkDependency).IsAssignableFrom(interfaceType)) { registration = registration.InstancePerMatchingLifetimeScope("work"); } else if (typeof(ITransientDependency).IsAssignableFrom(interfaceType)) { registration = registration.InstancePerDependency(); } } if (!typeof(IEventHandler).IsAssignableFrom(item.Type)) { continue; } var interfaces = item.Type.GetInterfaces(); foreach (var interfaceType in interfaces) { if (interfaceType.GetInterface(typeof(IEventHandler).Name) != null) { registration = registration.Named <IEventHandler>(interfaceType.Name); } } } _shellContainerRegistrationses.Invoke(i => i.Registrations(builder, blueprint), NullLogger.Instance); })); }
public ICommandContext CreateContext(ICommandActor actor, string[] args, string prefix, IEnumerable <ICommandRegistration> commandRegistrations) { var rootCommand = GetCommandRegistration(actor, args[0], commandRegistrations.Where(d => d.ParentId == null)); if (rootCommand == null) { var exceptionContext = new CommandContext(null, actor, args.First(), prefix, args.Skip(1).ToList(), m_LifetimeScope.BeginLifetimeScope()); var localizer = m_LifetimeScope.Resolve <IOpenModStringLocalizer>(); exceptionContext.Exception = new CommandNotFoundException(localizer["commands:errors:not_found", new { CommandName = args[0], Args = args }]); //await actor.PrintMessageAsync(Color.Red, exceptionContext.Exception.Message); return(exceptionContext); } var scope = rootCommand.Component.LifetimeScope.BeginLifetimeScope($"Command context scope for \"{string.Join(" ", args)}\" by actor {actor.Type}/{actor.DisplayName} ({actor.Id})"); var rootContext = new CommandContext(rootCommand, actor, args.First(), prefix, args.Skip(1).ToList(), scope); return(BuildContextTree(rootContext, commandRegistrations)); }
public IDisposable Begin() { return(_nestedLifetimeScope.Value = _lifetimeScope.BeginLifetimeScope("Quidjibo")); }
public IDependencyScope BeginScope() { return(new AutofacDependencyScope(_scope.BeginLifetimeScope("Mediator.Net"))); }
public MessageServiceHub(ILifetimeScope lifetimeScope) : base() { this._lifetimeScope = lifetimeScope.BeginLifetimeScope("AutofacWebRequest"); this._messageService = this._lifetimeScope.Resolve<IMessageService>(); this._membershipService = this._lifetimeScope.Resolve<IMembershipService>(); }
public async Task <IOpenModPlugin> TryActivatePluginAsync(Assembly assembly) { try { if (m_IsDisposing) { throw new ObjectDisposedException(nameof(PluginActivator)); } var pluginMetadata = assembly.GetCustomAttribute <PluginMetadataAttribute>(); if (pluginMetadata == null) { m_Logger.LogError( $"Failed to load plugin from assembly {assembly}: couldn't find any plugin metadata"); return(null); } var pluginTypes = assembly.FindTypes <IOpenModPlugin>(false).ToList(); if (pluginTypes.Count == 0) { m_Logger.LogError( $"Failed to load plugin from assembly {assembly}: couldn't find any IOpenModPlugin implementation"); return(null); } if (pluginTypes.Count > 1) { m_Logger.LogError( $"Failed to load plugin from assembly {assembly}: assembly has multiple IOpenModPlugin instances"); return(null); } var pluginType = pluginTypes.Single(); IOpenModPlugin pluginInstance; try { var serviceProvider = m_LifetimeScope.Resolve <IServiceProvider>(); var lifetimeScope = m_LifetimeScope.BeginLifetimeScope(containerBuilder => { var workingDirectory = PluginHelper.GetWorkingDirectory(m_Runtime, pluginMetadata.Id); var configurationBuilder = new ConfigurationBuilder(); if (Directory.Exists(workingDirectory)) { configurationBuilder .SetBasePath(workingDirectory) .AddYamlFile("config.yaml", optional: true, reloadOnChange: true); } var configuration = configurationBuilder .AddEnvironmentVariables(pluginMetadata.Id.Replace(".", "_") + "_") .Build(); containerBuilder.Register(context => configuration) .As <IConfiguration>() .As <IConfigurationRoot>() .SingleInstance() .OwnedByLifetimeScope(); containerBuilder.RegisterType(pluginType) .AsSelf() .As <IOpenModComponent>() .As <IOpenModPlugin>() .SingleInstance() .OwnedByLifetimeScope(); containerBuilder.RegisterType <ScopedPermissionChecker>() .As <IPermissionChecker>() .InstancePerLifetimeScope() .OwnedByLifetimeScope(); containerBuilder.Register(context => m_DataStoreFactory.CreateDataStore(new DataStoreCreationParameters { ComponentId = pluginMetadata.Id, Prefix = null, Suffix = "data", WorkingDirectory = workingDirectory })) .As <IDataStore>() .SingleInstance() .OwnedByLifetimeScope(); var stringLocalizer = Directory.Exists(workingDirectory) ? m_StringLocalizerFactory.Create("translations", workingDirectory) : NullStringLocalizer.Instance; containerBuilder.Register(context => stringLocalizer) .As <IStringLocalizer>() .SingleInstance() .OwnedByLifetimeScope(); var services = ServiceRegistrationHelper.FindFromAssembly <PluginServiceImplementationAttribute>(assembly, m_Logger); var servicesRegistrations = services.OrderBy(d => d.Priority, new PriorityComparer(PriortyComparisonMode.LowestFirst)); foreach (var servicesRegistration in servicesRegistrations) { var implementationType = servicesRegistration.ServiceImplementationType; containerBuilder.RegisterType(implementationType) .As(implementationType) .WithLifetime(servicesRegistration.Lifetime) .OwnedByLifetimeScope(); foreach (var service in servicesRegistration.ServiceTypes) { containerBuilder.Register(c => c.Resolve(implementationType)) .As(service) .WithLifetime(servicesRegistration.Lifetime) .OwnedByLifetimeScope(); } } foreach (var type in pluginType.Assembly.FindTypes <IPluginContainerConfigurator>()) { var configurator = (IPluginContainerConfigurator)ActivatorUtilities.CreateInstance(serviceProvider, type); configurator.ConfigureContainer(new PluginServiceConfigurationContext(m_LifetimeScope, configuration, containerBuilder)); } var configurationEvent = new PluginContainerConfiguringEvent(pluginMetadata, pluginType, configuration, containerBuilder, workingDirectory); AsyncHelper.RunSync(() => m_EventBus.EmitAsync(m_Runtime, this, configurationEvent)); }); pluginInstance = (IOpenModPlugin)lifetimeScope.Resolve(pluginType); var pluginActivateEvent = new PluginActivatingEvent(pluginInstance); await m_EventBus.EmitAsync(m_Runtime, this, pluginActivateEvent); if (pluginActivateEvent.IsCancelled) { await lifetimeScope.DisposeAsync(); return(null); } } catch (Exception ex) { m_Logger.LogError(ex, $"Failed to load plugin from type: {pluginType.FullName} in assembly: {assembly.FullName}"); return(null); } try { await pluginInstance.LoadAsync(); var serviceProvider = pluginInstance.LifetimeScope.Resolve <IServiceProvider>(); var pluginHelpWriter = ActivatorUtilities.CreateInstance <PluginHelpWriter>(serviceProvider); await pluginHelpWriter.WriteHelpFileAsync(); } catch (Exception ex) { m_Logger.LogError(ex, $"Failed to load plugin: {pluginInstance.DisplayName} v{pluginInstance.Version}"); try { await pluginInstance.LifetimeScope.DisposeAsync(); } catch (Exception e) { m_Logger.LogError(e, "Failed to unload plugin: {DisplayName} v{Version}", pluginInstance.DisplayName, pluginInstance.Version); } return(null); } m_ActivatedPlugins.Add(new WeakReference(pluginInstance)); return(pluginInstance); } catch (Exception ex) { m_Logger.LogError(ex, $"Failed to load plugin from assembly: {assembly.FullName}"); return(null); } }
/// <summary> /// Begin a new sub-scope. Instances created via the sub-scope /// will be disposed along with it. /// </summary> /// <returns>A new lifetime scope.</returns> public ILifetimeScope BeginLifetimeScope() { return(_rootLifetimeScope.BeginLifetimeScope()); }
public IRepositoryScope BeginRepositoryScope() { return(new RepositoryScope(_lifetimeScope.BeginLifetimeScope())); }
public void resolve_JobTimerDbContext() { _sut.BeginLifetimeScope().Resolve <JobTimerDbContext>().Should().BeOfType <JobTimerDbContext>(); }
public ContentScope(Type type, object key, ILifetimeScope parentScope, params Parameter[] parameters) { scope = parentScope.BeginLifetimeScope(); Content = scope.ResolveKeyed(key, type, parameters) as IContentViewModel; }
private async Task <IEnumerable <IValidationError> > RunValidation(ValidationActorModel actorModel, CancellationToken cancellationToken) { if (_executionContext is ExecutionContext executionContextObj) { executionContextObj.JobId = "-1"; executionContextObj.TaskKey = _actorId.ToString(); } ILogger logger = _parentLifeTimeScope.Resolve <ILogger>(); InternalDataCache internalDataCache; ExternalDataCache externalDataCache; FileDataCache fileDataCache; Message message; ValidationContext validationContext; IEnumerable <IValidationError> errors; try { logger.LogDebug($"{nameof(ValidationActor)} {_actorId} {GC.GetGeneration(actorModel)} starting"); internalDataCache = _jsonSerializationService.Deserialize <InternalDataCache>(Encoding.UTF8.GetString(actorModel.InternalDataCache)); externalDataCache = _jsonSerializationService.Deserialize <ExternalDataCache>(Encoding.UTF8.GetString(actorModel.ExternalDataCache)); fileDataCache = _jsonSerializationService.Deserialize <FileDataCache>(Encoding.UTF8.GetString(actorModel.FileDataCache)); message = _jsonSerializationService.Deserialize <Message>(new MemoryStream(actorModel.Message)); validationContext = new ValidationContext { Input = message }; logger.LogDebug($"{nameof(ValidationActor)} {_actorId} {GC.GetGeneration(actorModel)} finished getting input data"); cancellationToken.ThrowIfCancellationRequested(); } catch (Exception ex) { ActorEventSource.Current.ActorMessage(this, "Exception-{0}", ex.ToString()); logger.LogError($"Error while processing {nameof(ValidationActor)}", ex); throw; } using (var childLifeTimeScope = _parentLifeTimeScope.BeginLifetimeScope(c => { c.RegisterInstance(validationContext).As <IValidationContext>(); c.RegisterInstance(new Cache <IMessage> { Item = message }).As <ICache <IMessage> >(); c.RegisterInstance(internalDataCache).As <IInternalDataCache>(); c.RegisterInstance(externalDataCache).As <IExternalDataCache>(); c.RegisterInstance(fileDataCache).As <IFileDataCache>(); })) { ExecutionContext executionContext = (ExecutionContext)childLifeTimeScope.Resolve <IExecutionContext>(); executionContext.JobId = actorModel.JobId; executionContext.TaskKey = _actorId.ToString(); ILogger jobLogger = childLifeTimeScope.Resolve <ILogger>(); try { jobLogger.LogDebug($"{nameof(ValidationActor)} {_actorId} {GC.GetGeneration(actorModel)} {executionContext.TaskKey} started learners: {validationContext.Input.Learners.Count}"); IRuleSetOrchestrationService <ILearner, IValidationError> preValidationOrchestrationService = childLifeTimeScope .Resolve <IRuleSetOrchestrationService <ILearner, IValidationError> >(); errors = await preValidationOrchestrationService.Execute(cancellationToken); jobLogger.LogDebug($"{nameof(ValidationActor)} {_actorId} {GC.GetGeneration(actorModel)} {executionContext.TaskKey} validation done"); } catch (Exception ex) { ActorEventSource.Current.ActorMessage(this, "Exception-{0}", ex.ToString()); jobLogger.LogError($"Error while processing {nameof(ValidationActor)}", ex); throw; } } internalDataCache = null; externalDataCache = null; fileDataCache = null; message = null; validationContext = null; return(errors); }
public INestedLifetime CreateLifetime() { var nestedScope = _lifetimeScope.BeginLifetimeScope(); return(nestedScope.Resolve <Lifetime>()); }
public ILifetimeScope CreateContainer(ShellSettings settings, ShellBlueprint blueprint) { var intermediateScope = _lifetimeScope.BeginLifetimeScope( builder => { foreach (var item in blueprint.Dependencies.Where(t => typeof(IModule).IsAssignableFrom(t.Type))) { var registration = RegisterType(builder, item) .Keyed <IModule>(item.Type) .InstancePerDependency(); foreach (var parameter in item.Parameters) { registration = registration .WithParameter(parameter.Name, parameter.Value) .WithProperty(parameter.Name, parameter.Value); } } }); return(intermediateScope.BeginLifetimeScope( "shell", builder => { var dynamicProxyContext = new DynamicProxyContext(); builder.Register(ctx => dynamicProxyContext); builder.Register(ctx => settings); builder.Register(ctx => blueprint.Descriptor); builder.Register(ctx => blueprint); var moduleIndex = intermediateScope.Resolve <IIndex <Type, IModule> >(); foreach (var item in blueprint.Dependencies.Where(t => typeof(IModule).IsAssignableFrom(t.Type))) { builder.RegisterModule(moduleIndex[item.Type]); } foreach (var item in blueprint.Dependencies.Where(t => typeof(IDependency).IsAssignableFrom(t.Type))) { var registration = RegisterType(builder, item) .EnableDynamicProxy(dynamicProxyContext) .InstancePerLifetimeScope(); foreach (var interfaceType in item.Type.GetInterfaces() .Where(itf => typeof(IDependency).IsAssignableFrom(itf) && !typeof(IEventHandler).IsAssignableFrom(itf))) { registration = registration.As(interfaceType); if (typeof(ISingletonDependency).IsAssignableFrom(interfaceType)) { registration = registration.InstancePerMatchingLifetimeScope("shell"); } else if (typeof(IUnitOfWorkDependency).IsAssignableFrom(interfaceType)) { registration = registration.InstancePerMatchingLifetimeScope("work"); } else if (typeof(ITransientDependency).IsAssignableFrom(interfaceType)) { registration = registration.InstancePerDependency(); } } if (typeof(IEventHandler).IsAssignableFrom(item.Type)) { var interfaces = item.Type.GetInterfaces(); foreach (var interfaceType in interfaces) { // register named instance for each interface, for efficient filtering inside event bus // IEventHandler derived classes only if (interfaceType.GetInterface(typeof(IEventHandler).Name) != null) { registration = registration.Named <IEventHandler>(interfaceType.Name); } } } foreach (var parameter in item.Parameters) { registration = registration .WithParameter(parameter.Name, parameter.Value) .WithProperty(parameter.Name, parameter.Value); } } foreach (var item in blueprint.Controllers) { var serviceKeyName = (item.AreaName + "/" + item.ControllerName).ToLowerInvariant(); var serviceKeyType = item.Type; RegisterType(builder, item) .EnableDynamicProxy(dynamicProxyContext) .Keyed <IController>(serviceKeyName) .Keyed <IController>(serviceKeyType) .WithMetadata("ControllerType", item.Type) .InstancePerDependency() .OnActivating(e => { // necessary to inject custom filters dynamically // see FilterResolvingActionInvoker var controller = e.Instance as Controller; if (controller != null) { controller.ActionInvoker = (IActionInvoker)e.Context.ResolveService(new TypedService(typeof(IActionInvoker))); } }); } foreach (var item in blueprint.HttpControllers) { var serviceKeyName = (item.AreaName + "/" + item.ControllerName).ToLowerInvariant(); var serviceKeyType = item.Type; RegisterType(builder, item) .EnableDynamicProxy(dynamicProxyContext) .Keyed <IHttpController>(serviceKeyName) .Keyed <IHttpController>(serviceKeyType) .WithMetadata("ControllerType", item.Type) .InstancePerDependency(); } // Register code-only registrations specific to a shell _shellContainerRegistrations.Registrations(builder); var optionalShellConfig = HostingEnvironment.MapPath("~/Config/Sites.config"); if (File.Exists(optionalShellConfig)) { builder.RegisterModule(new ConfigurationSettingsReader(ConfigurationSettingsReaderConstants.DefaultSectionName, optionalShellConfig)); } var optionalShellByNameConfig = HostingEnvironment.MapPath("~/Config/Sites." + settings.Name + ".config"); if (File.Exists(optionalShellByNameConfig)) { builder.RegisterModule(new ConfigurationSettingsReader(ConfigurationSettingsReaderConstants.DefaultSectionName, optionalShellByNameConfig)); } })); }
//private void OnScopeBeginning(object sender, LifetimeScopeBeginningEventArgs args) //{ // bool isWeb = System.Web.HttpContext.Current != null; // Debug.WriteLine("Scope Begin, Web: " + isWeb); //} //private void OnScopeEnding(object sender, LifetimeScopeEndingEventArgs args) //{ // bool isWeb = System.Web.HttpContext.Current != null; // Debug.WriteLine("Scope END, Web: " + isWeb); //} private ILifetimeScope BeginLifetimeScope(Action <ContainerBuilder> configurationAction) { return((configurationAction == null) ? _rootContainer.BeginLifetimeScope(ScopeTag) : _rootContainer.BeginLifetimeScope(ScopeTag, configurationAction)); }
public void InitializeInstanceContext(InstanceContext instanceContext, Message message, IContextChannel channel) { new InstanceContextExtension(instanceContext, scope.BeginLifetimeScope(), channel); }
ILifetimeScope CreateScope() { return(_parentScope.BeginLifetimeScope(_tag, x => _configurator(_id, x))); }
/// <summary> /// This is used to import renewals from 1.9.x /// </summary> /// <param name="main"></param> /// <param name="fromUri"></param> /// <param name="toUri"></param> /// <returns></returns> public ILifetimeScope Legacy(ILifetimeScope main, Uri fromUri, Uri toUri) { return(main.BeginLifetimeScope(builder => { var realSettings = main.Resolve <ISettingsService>(); var realArguments = main.Resolve <IArgumentsService>(); builder.Register(c => new MainArguments { BaseUri = fromUri.ToString() }). As <MainArguments>(). SingleInstance(); builder.RegisterType <ArgumentsService>(). As <IArgumentsService>(). SingleInstance(); builder.RegisterType <LegacySettingsService>(). WithParameter(new TypedParameter(typeof(ISettingsService), realSettings)). SingleInstance(); builder.RegisterType <LegacyTaskSchedulerService>(); builder.RegisterType <TaskSchedulerService>(). WithParameter(new TypedParameter(typeof(IArgumentsService), realArguments)). WithParameter(new TypedParameter(typeof(ISettingsService), realSettings)). SingleInstance(); builder.Register((scope) => main.Resolve <IRenewalStore>()). As <IRenewalStore>(). SingleInstance(); // Check where to load Renewals from var hive = Registry.CurrentUser; var key = hive.OpenSubKey($"Software\\letsencrypt-win-simple"); if (key == null) { hive = Registry.LocalMachine; key = hive.OpenSubKey($"Software\\letsencrypt-win-simple"); } var log = main.Resolve <ILogService>(); if (key != null) { log.Debug("Loading legacy renewals from registry hive {name}", hive.Name); builder.RegisterType <RegistryLegacyRenewalService>(). As <ILegacyRenewalService>(). WithParameter(new NamedParameter("hive", hive.Name)). SingleInstance(); } else { log.Debug("Loading legacy renewals from file"); builder.RegisterType <FileLegacyRenewalService>(). As <ILegacyRenewalService>(). SingleInstance(); } builder.RegisterType <Importer>(). SingleInstance(); })); }
public IDependencyInjectionContainer GetTransactionalContainer() { ILifetimeScope lifetimeScope = _LifetimeScope.BeginLifetimeScope(); return(new AutofacDependencyInjectionContainer(lifetimeScope)); }
public IScopeResolver BeginScope() { return(new AutofacScopeResolver(_lifetimeScope.BeginLifetimeScope())); }
static ILifetimeScope InitializeLifetimeScope(Action<ContainerBuilder> configurationAction, ILifetimeScope container) { return (configurationAction == null) ? container.BeginLifetimeScope(HttpRequestTag) : container.BeginLifetimeScope(HttpRequestTag, configurationAction); }
public JobsHub(ILifetimeScope lifetimeScope) { _hubLifetimeScope = lifetimeScope.BeginLifetimeScope(); }
public static ILifetimeScope BeginLifetimeScope(ILifetimeScope scope, HttpRequestMessage request) { var inner = scope.BeginLifetimeScope(LifetimeScopeTag); inner.Resolve<HttpRequestMessage>(TypedParameter.From(request)); return inner; }
private ILifetimeScope GetInnerScope() { return(lifetimeScope.BeginLifetimeScope(b => b.RegisterType <TResult>().ExternallyOwned())); }
/// <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> /// <param name="childSpecificConfigurationAction"> /// An Autofac configuration action the will be run upon creation of the child scope /// (i.e. container registrations specific to the new child scope) /// </param> /// <returns>The child scope for the uniquely identified resource</returns> public ILifetimeScope GetChildLifetimeScope( ILifetimeScope parentScope, string scopeKindTag, string childScopeKey, Action<ContainerBuilder> childSpecificConfigurationAction) { 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, childSpecificConfigurationAction); this.childScopes[childScopeKey] = ensuredScope; } } } return ensuredScope; }
public IDIContainer CreateContainer() { return(new DIContainerForAutofac(_containerBuilder, _lifetimeScope.BeginLifetimeScope())); }
public IServiceResolver CreateScope() { return(new AutofacServiceResolver(_lifetimeScope.BeginLifetimeScope())); }
protected AutofacScope(ILifetimeScope scope) { _scope = scope.BeginLifetimeScope(); }
public void Setup() { _hostContainer = new ContainerBuilder().Build().BeginLifetimeScope(DreamContainerScope.Host); _serviceContainer = _hostContainer.BeginLifetimeScope(DreamContainerScope.Service); _requestContainer = _serviceContainer.BeginLifetimeScope(DreamContainerScope.Request); }
/// <summary> /// Returns a child instance of the container to facilitate deterministic disposal /// of all resources built by the child container. /// </summary> /// <returns></returns> public Common.IContainer BuildChildContainer() { return(new AutofacObjectBuilder(container.BeginLifetimeScope())); }
public async Task SendAsync <TCommand>(TCommand command, ICorrelation correlation, CancellationToken cancellationToken = default) where TCommand : ICommand { await using var scope = _scope.BeginLifetimeScope(); await scope.Resolve <IReceiveLoopbackCommand>().ReceiveAsync(command, correlation, cancellationToken); }