Ejemplo n.º 1
0
        public ShellBlueprint Compose(ShellSettings settings, ShellDescriptor descriptor)
        {
            if (_logger.IsEnabled(LogLevel.Debug))
            {
                _logger.LogDebug("Composing blueprint");
            }

            var enabledFeatures = _extensionManager.EnabledFeatures(descriptor);
            var features        = _extensionManager.LoadFeatures(enabledFeatures);

            // Requiring "Orchard.Hosting" is a shortcut for adding all referenced
            // assemblies as features.
            // TODO: Remove once all services are registered explicitly, so that the container factory
            // doesn't need to inspect ExportedTypes for the core assemblies. We can then also remove
            // some references from Orchard.Hosting.Web.

            if (descriptor.Features.Any(feature => feature.Name == "Orchard.Hosting"))
            {
                features = BuiltinFeatures().Concat(features);
            }

            var excludedTypes = GetExcludedTypes(features);

            var modules      = BuildBlueprint(features, IsModule, BuildModule, excludedTypes);
            var dependencies = BuildBlueprint(features, IsDependency, (t, f) => BuildDependency(t, f, descriptor),
                                              excludedTypes);

            var uniqueDependencies = new Dictionary <Type, DependencyBlueprint>();

            foreach (var dependency in dependencies)
            {
                if (!uniqueDependencies.ContainsKey(dependency.Type))
                {
                    uniqueDependencies.Add(dependency.Type, dependency);
                }
            }

            foreach (var dependency in modules)
            {
                if (!uniqueDependencies.ContainsKey(dependency.Type))
                {
                    uniqueDependencies.Add(dependency.Type, dependency);
                }
            }

            var result = new ShellBlueprint
            {
                Settings     = settings,
                Descriptor   = descriptor,
                Dependencies = uniqueDependencies.Values
            };

            if (_logger.IsEnabled(LogLevel.Debug))
            {
                _logger.LogDebug("Done composing blueprint");
            }
            return(result);
        }
Ejemplo n.º 2
0
        public void PopulateFeature(IEnumerable <ApplicationPart> parts, ControllerFeature feature)
        {
            ShellBlueprint blue = SchubertEngine.Current.GetRequiredService <ShellBlueprint>();

            foreach (var c in blue.Controllers)
            {
                feature.Controllers.Add(c.Type.GetTypeInfo());
            }
        }
        public SessionConfigurationCache(ShellSettings shellSettings, ShellBlueprint shellBlueprint, IAppDataFolder appDataFolder, IHostEnvironment hostEnvironment)
        {
            _shellSettings   = shellSettings;
            _shellBlueprint  = shellBlueprint;
            _appDataFolder   = appDataFolder;
            _hostEnvironment = hostEnvironment;
            _currentConfig   = null;

            Logger = NullLogger.Instance;
        }
Ejemplo n.º 4
0
        public IServiceProvider CreateContainer(ShellSettings settings, ShellBlueprint blueprint)
        {
            ServiceCollection serviceCollection = new ServiceCollection();

            serviceCollection.AddScoped <IOrchardShell, DefaultOrchardShell>();
            serviceCollection.AddScoped <IRouteBuilder, DefaultShellRouteBuilder>();
            serviceCollection.AddInstance(settings);
            serviceCollection.AddInstance(blueprint.Descriptor);
            serviceCollection.AddInstance(blueprint);

            foreach (var dependency in blueprint.Dependencies
                     .Where(t => typeof(IModule).IsAssignableFrom(t.Type)))
            {
                Logger.Debug("IModule Type: {0}", dependency.Type);

                // TODO: Rewrite to get rid of reflection.
                var instance = (IModule)Activator.CreateInstance(dependency.Type);
                instance.Configure(serviceCollection);
            }

            var p = _serviceProvider.GetService <IOrchardLibraryManager>();

            serviceCollection.AddInstance <IAssemblyProvider>(new DefaultAssemblyProviderTest(p, _serviceProvider, _serviceProvider.GetService <IAssemblyLoaderContainer>()));

            foreach (var dependency in blueprint.Dependencies
                     .Where(t => !typeof(IModule).IsAssignableFrom(t.Type)))
            {
                foreach (var interfaceType in dependency.Type.GetInterfaces()
                         .Where(itf => typeof(IDependency).IsAssignableFrom(itf)))
                {
                    Logger.Debug("Type: {0}, Interface Type: {1}", dependency.Type, interfaceType);

                    if (typeof(ISingletonDependency).IsAssignableFrom(interfaceType))
                    {
                        serviceCollection.AddSingleton(interfaceType, dependency.Type);
                    }
                    else if (typeof(IUnitOfWorkDependency).IsAssignableFrom(interfaceType))
                    {
                        serviceCollection.AddScoped(interfaceType, dependency.Type);
                    }
                    else if (typeof(ITransientDependency).IsAssignableFrom(interfaceType))
                    {
                        serviceCollection.AddTransient(interfaceType, dependency.Type);
                    }
                    else
                    {
                        serviceCollection.AddScoped(interfaceType, dependency.Type);
                    }
                }
            }

            serviceCollection.AddLogging();

            return(new WrappingServiceProvider(_serviceProvider, serviceCollection));
        }
        public IServiceProvider CreateContainer(ShellSettings settings, ShellBlueprint blueprint)
        {
            IServiceCollection serviceCollection = new ServiceCollection();

            serviceCollection.AddInstance(settings);
            serviceCollection.AddInstance(blueprint.Descriptor);
            serviceCollection.AddInstance(blueprint);

            // Sure this is right?
            serviceCollection.AddInstance(_loggerFactory);

            IServiceCollection moduleServiceCollection = new ServiceCollection();

            foreach (var dependency in blueprint.Dependencies
                     .Where(t => typeof(IModule).IsAssignableFrom(t.Type)))
            {
                moduleServiceCollection.AddScoped(typeof(IModule), dependency.Type);
            }

            var moduleServiceProvider = moduleServiceCollection.BuildShellServiceProviderWithHost(_serviceProvider);

            foreach (var service in moduleServiceProvider.GetServices <IModule>())
            {
                service.Configure(serviceCollection);
            }

            foreach (var dependency in blueprint.Dependencies
                     .Where(t => !typeof(IModule).IsAssignableFrom(t.Type)))
            {
                foreach (var interfaceType in dependency.Type.GetInterfaces()
                         .Where(itf => typeof(IDependency).IsAssignableFrom(itf)))
                {
                    _logger.LogDebug("Type: {0}, Interface Type: {1}", dependency.Type, interfaceType);

                    if (typeof(ISingletonDependency).IsAssignableFrom(interfaceType))
                    {
                        serviceCollection.AddSingleton(interfaceType, dependency.Type);
                    }
                    else if (typeof(IUnitOfWorkDependency).IsAssignableFrom(interfaceType))
                    {
                        serviceCollection.AddScoped(interfaceType, dependency.Type);
                    }
                    else if (typeof(ITransientDependency).IsAssignableFrom(interfaceType))
                    {
                        serviceCollection.AddTransient(interfaceType, dependency.Type);
                    }
                    else
                    {
                        serviceCollection.AddScoped(interfaceType, dependency.Type);
                    }
                }
            }

            return(serviceCollection.BuildShellServiceProviderWithHost(_serviceProvider));
        }
Ejemplo n.º 6
0
        public ShellBlueprint Compose(ShellSettings settings, ShellDescriptor descriptor)
        {
            if (_logger.IsEnabled(LogLevel.Debug))
            {
                _logger.LogDebug("Composing blueprint");
            }

            var enabledFeatures = _extensionManager.EnabledFeatures(descriptor);
            var features        = _extensionManager.LoadFeatures(enabledFeatures);

            // Requiring "Orchard.Hosting" is a shortcut for adding all referenced
            // assemblies as features
            if (descriptor.Features.Any(feature => feature.Name == "Orchard.Hosting"))
            {
                features = BuiltinFeatures().Concat(features);
            }

            var excludedTypes = GetExcludedTypes(features);

            var modules      = BuildBlueprint(features, IsModule, BuildModule, excludedTypes);
            var dependencies = BuildBlueprint(features, IsDependency, (t, f) => BuildDependency(t, f, descriptor),
                                              excludedTypes);

            var uniqueDependencies = new Dictionary <Type, DependencyBlueprint>();

            foreach (var dependency in dependencies)
            {
                if (!uniqueDependencies.ContainsKey(dependency.Type))
                {
                    uniqueDependencies.Add(dependency.Type, dependency);
                }
            }

            foreach (var dependency in modules)
            {
                if (!uniqueDependencies.ContainsKey(dependency.Type))
                {
                    uniqueDependencies.Add(dependency.Type, dependency);
                }
            }

            var result = new ShellBlueprint
            {
                Settings     = settings,
                Descriptor   = descriptor,
                Dependencies = uniqueDependencies.Values
            };

            if (_logger.IsEnabled(LogLevel.Debug))
            {
                _logger.LogDebug("Done composing blueprint");
            }
            return(result);
        }
        public ShellBlueprint Compose(ShellSettings settings, ShellDescriptor descriptor)
        {
            Logger.Debug("Composing blueprint");

            var builtinFeatures           = BuiltinFeatures().ToList();
            var builtinFeatureDescriptors = builtinFeatures.Select(x => x.Descriptor).ToList();
            var availableFeatures         = _extensionManager.AvailableFeatures()
                                            .Concat(builtinFeatureDescriptors)
                                            .GroupBy(x => x.Id.ToLowerInvariant()) // prevent duplicates
                                            .Select(x => x.FirstOrDefault())
                                            .ToDictionary(x => x.Id, StringComparer.OrdinalIgnoreCase);
            var enabledFeatures  = _extensionManager.EnabledFeatures(descriptor).Select(x => x.Id).ToList();
            var expandedFeatures = ExpandDependencies(availableFeatures, descriptor.Features.Select(x => x.Name)).ToList();
            var autoEnabledDependencyFeatures = expandedFeatures.Except(enabledFeatures).Except(builtinFeatureDescriptors.Select(x => x.Id)).ToList();
            var featureDescriptors            = _extensionManager.EnabledFeatures(expandedFeatures.Select(x => new ShellFeature {
                Name = x
            })).ToList();
            var features = _extensionManager.LoadFeatures(featureDescriptors);

            if (descriptor.Features.Any(feature => feature.Name == "Boying.Framework"))
            {
                features = builtinFeatures.Concat(features);
            }

            var excludedTypes   = GetExcludedTypes(features);
            var modules         = BuildBlueprint(features, IsModule, BuildModule, excludedTypes);
            var dependencies    = BuildBlueprint(features, IsDependency, (t, f) => BuildDependency(t, f, descriptor), excludedTypes);
            var controllers     = BuildBlueprint(features, IsController, BuildController, excludedTypes);
            var httpControllers = BuildBlueprint(features, IsHttpController, BuildController, excludedTypes);
            var records         = BuildBlueprint(features, IsRecord, (t, f) => BuildRecord(t, f, settings), excludedTypes);

            var result = new ShellBlueprint
            {
                Settings        = settings,
                Descriptor      = descriptor,
                Dependencies    = dependencies.Concat(modules).ToArray(),
                Controllers     = controllers,
                HttpControllers = httpControllers,
                Records         = records,
            };

            Logger.Debug("Done composing blueprint.");

            if (autoEnabledDependencyFeatures.Any())
            {
                // Add any dependencies previously not enabled to the shell descriptor.
                descriptor.Features = descriptor.Features.Concat(autoEnabledDependencyFeatures.Select(x => new ShellFeature {
                    Name = x
                })).ToList();
                Logger.Information("Automatically enabled the following dependency features: {0}.", String.Join(", ", autoEnabledDependencyFeatures));
            }

            return(result);
        }
Ejemplo n.º 8
0
 public DataRepository(ISessionLocator sessionLocator,
                       ShellSettings shellSettings,
                       ShellBlueprint shellBlueprint,
                       IAppDataFolder appDataFolder,
                       IJsonDataRepositoryFactoryHolder jsonDataRepositoryFactoryHolder)
 {
     _sessionLocator = sessionLocator;
     _shellSettings  = shellSettings;
     _shellBlueprint = shellBlueprint;
     _appDataFolder  = appDataFolder;
     _jsonDataRepositoryFactoryHolder = jsonDataRepositoryFactoryHolder;
     Logger = NullLogger.Instance;
 }
Ejemplo n.º 9
0
        public void ExtensionDisplayNameShouldBeUsedInBothStandardRoutes()
        {
            var blueprint = new ShellBlueprint {
                Controllers = new[] {
                    new ControllerBlueprint {
                        AreaName = "Long.Name.Foo",
                        Feature  = new Feature {
                            Descriptor = new FeatureDescriptor {
                                Extension = new ExtensionDescriptor {
                                    Id   = "Foo",
                                    Name = "A Foo Module",
                                    Path = "Foo"
                                }
                            }
                        }
                    },
                    new ControllerBlueprint {
                        AreaName = "Long.Name.Bar",
                        Feature  = new Feature {
                            Descriptor = new FeatureDescriptor {
                                Extension = new ExtensionDescriptor {
                                    Id   = "Bar",
                                    Name = "Bar",
                                    Path = "BarBar"
                                }
                            }
                        }
                    }
                }
            };
            var routeProvider = new StandardExtensionRouteProvider(blueprint);

            var routes = new List <RouteDescriptor>();

            routeProvider.GetRoutes(routes);

            Assert.Equal(routes.Count, 4);
            var fooAdmin = routes.Select(x => x.Route).OfType <Route>()
                           .Single(x => x.Url == "Admin/Foo/{action}/{id}");
            var fooRoute = routes.Select(x => x.Route).OfType <Route>()
                           .Single(x => x.Url == "Foo/{controller}/{action}/{id}");
            var barAdmin = routes.Select(x => x.Route).OfType <Route>()
                           .Single(x => x.Url == "Admin/BarBar/{action}/{id}");
            var barRoute = routes.Select(x => x.Route).OfType <Route>()
                           .Single(x => x.Url == "BarBar/{controller}/{action}/{id}");

            Assert.Equal(fooAdmin.DataTokens["area"], ("Long.Name.Foo"));
            Assert.Equal(fooRoute.DataTokens["area"], ("Long.Name.Foo"));
            Assert.Equal(barAdmin.DataTokens["area"], ("Long.Name.Bar"));
            Assert.Equal(barRoute.DataTokens["area"], ("Long.Name.Bar"));
        }
        public void NormalExecutionReturnsExpectedObjects()
        {
            var settings = new ShellSettings {
                Name = ShellSettings.DefaultName
            };
            var descriptor = new ShellDescriptor {
                SerialNumber = 6655321
            };
            var blueprint          = new ShellBlueprint();
            var shellLifetimeScope = _container.BeginLifetimeScope("shell");
            var httpContext        = new StubHttpContext();

            _container.Mock <IShellDescriptorCache>()
            .Setup(x => x.Fetch(ShellSettings.DefaultName))
            .Returns(descriptor);

            _container.Mock <ICompositionStrategy>()
            .Setup(x => x.Compose(settings, descriptor))
            .Returns(blueprint);

            _container.Mock <IShellContainerFactory>()
            .Setup(x => x.CreateContainer(settings, blueprint))
            .Returns(shellLifetimeScope);

            _container.Mock <IShellDescriptorManager>()
            .Setup(x => x.GetShellDescriptor())
            .Returns(descriptor);

            _container.Mock <IWorkContextEvents>()
            .Setup(x => x.Started());

            _container.Mock <IHttpContextAccessor>()
            .Setup(x => x.Current())
            .Returns(httpContext);

            _container.Mock <IHttpContextAccessor>()
            .Setup(x => x.CreateContext(It.IsAny <ILifetimeScope>()))
            .Returns(httpContext);

            var factory = _container.Resolve <IShellContextFactory>();

            var context = factory.CreateShellContext(settings);

            Assert.That(context.Settings, Is.SameAs(settings));
            Assert.That(context.Descriptor, Is.SameAs(descriptor));
            Assert.That(context.Blueprint, Is.SameAs(blueprint));
            Assert.That(context.LifetimeScope, Is.SameAs(shellLifetimeScope));
            Assert.That(context.Shell, Is.SameAs(shellLifetimeScope.Resolve <IOrchardShell>()));
        }
 public DataRepositoryFactory(
     ShellSettings shellSettings,
     ShellBlueprint shellBlueprint,
     IAppDataFolder appDataFolder,
     IJsonDataRepositoryFactoryHolder jsonDataRepositoryFactoryHolder,
     ISessionFactoryHolderFactory sessionFactoryHolderFactory,
     ISessionLocator sessionLocator)
 {
     _shellSettings  = shellSettings;
     _shellBlueprint = shellBlueprint;
     _appDataFolder  = appDataFolder;
     _jsonDataRepositoryFactoryHolder = jsonDataRepositoryFactoryHolder;
     _sessionFactoryHolderFactory     = sessionFactoryHolderFactory;
     _sessionLocator = sessionLocator;
 }
        public ModuleGeneratorService(
            IOrchardServices orchardServices,
            IContentManager contentManager,
            ShellSettings shellSettings,
            ShellBlueprint shellBlueprint,
            IAppDataFolder appDataFolder)
        {
            _orchardServices = orchardServices;
            _contentManager  = contentManager;
            _shellSettings   = shellSettings;
            _shellBlueprint  = shellBlueprint;
            _appDataFolder   = appDataFolder;

            Logger = NullLogger.Instance;
        }
Ejemplo n.º 13
0
        public IServiceProvider CreateContainer(ShellSettings settings, ShellBlueprint blueprint)
        {
            IServiceCollection serviceCollection = new ServiceCollection();

            serviceCollection.AddInstance(settings);
            serviceCollection.AddInstance(blueprint.Descriptor);
            serviceCollection.AddInstance(blueprint);

            foreach (var dependency in blueprint.Dependencies
                     .Where(t => typeof(IModule).IsAssignableFrom(t.Type)))
            {
                _logger.LogDebug("IModule Type: {0}", dependency.Type);

                ((IModule)ActivatorUtilities
                 .CreateInstance(_serviceProvider, dependency.Type))
                .Configure(serviceCollection);
            }

            foreach (var dependency in blueprint.Dependencies
                     .Where(t => !typeof(IModule).IsAssignableFrom(t.Type)))
            {
                foreach (var interfaceType in dependency.Type.GetInterfaces()
                         .Where(itf => typeof(IDependency).IsAssignableFrom(itf)))
                {
                    _logger.LogDebug("Type: {0}, Interface Type: {1}", dependency.Type, interfaceType);

                    if (typeof(ISingletonDependency).IsAssignableFrom(interfaceType))
                    {
                        serviceCollection.AddSingleton(interfaceType, dependency.Type);
                    }
                    else if (typeof(IUnitOfWorkDependency).IsAssignableFrom(interfaceType))
                    {
                        serviceCollection.AddScoped(interfaceType, dependency.Type);
                    }
                    else if (typeof(ITransientDependency).IsAssignableFrom(interfaceType))
                    {
                        serviceCollection.AddTransient(interfaceType, dependency.Type);
                    }
                    else
                    {
                        serviceCollection.AddScoped(interfaceType, dependency.Type);
                    }
                }
            }

            return(new WrappingServiceProvider(_serviceProvider, serviceCollection));
        }
Ejemplo n.º 14
0
        public IServiceProvider CreateContainer(ShellSettings settings, ShellBlueprint blueprint)
        {
            ServiceCollection serviceCollection = new ServiceCollection();

            serviceCollection.AddScoped <IOrchardShell, DefaultOrchardShell>();
            serviceCollection.AddScoped <IRouteBuilder, DefaultShellRouteBuilder>();
            serviceCollection.AddInstance(settings);
            serviceCollection.AddInstance(blueprint.Descriptor);
            serviceCollection.AddInstance(blueprint);

            serviceCollection.AddScoped <ITypeActivator, TypeActivator>();

            serviceCollection.AddMvc();

            serviceCollection.Configure <RazorViewEngineOptions>(options => {
                var expander = new ModuleViewLocationExpander();
                options.ViewLocationExpanders.Add(expander);
            });

            foreach (var dependency in blueprint.Dependencies)
            {
                foreach (var interfaceType in dependency.Type.GetInterfaces()
                         .Where(itf => typeof(IDependency).IsAssignableFrom(itf)))
                {
                    Logger.Debug("Type: {0}, Interface Type: {1}", dependency.Type, interfaceType);

                    serviceCollection.AddScoped(interfaceType, dependency.Type);

                    if (typeof(ISingletonDependency).IsAssignableFrom(interfaceType))
                    {
                        serviceCollection.AddSingleton(interfaceType, dependency.Type);
                    }
                    else if (typeof(IUnitOfWorkDependency).IsAssignableFrom(interfaceType))
                    {
                        serviceCollection.AddScoped(interfaceType, dependency.Type);
                    }
                    else if (typeof(ITransientDependency).IsAssignableFrom(interfaceType))
                    {
                        serviceCollection.AddTransient(interfaceType, dependency.Type);
                    }
                }
            }

            return(BuildFallbackServiceProvider(
                       serviceCollection,
                       _serviceProvider));
        }
Ejemplo n.º 15
0
        public ContentsRepositoryFactory(
            ShellSettings shellSettings,
            ShellBlueprint shellBlueprint,
            IAppDataFolder appDataFolder,
            ISessionLocator sessionLocator,
            IOrchardServices orchardServices,
            IContentManager contentManager)
        {
            _shellSettings   = shellSettings;
            _shellBlueprint  = shellBlueprint;
            _appDataFolder   = appDataFolder;
            _sessionLocator  = sessionLocator;
            _orchardServices = orchardServices;
            _contentManager  = contentManager;

            Logger = NullLogger.Instance;
        }
Ejemplo n.º 16
0
        public async Task <ShellBlueprint> ComposeAsync(IShellSettings settings, IShellDescriptor descriptor)
        {
            if (_logger.IsEnabled(LogLevel.Debug))
            {
                _logger.LogDebug($"Composing blueprint for tennet {settings.Name} ");
            }

            // Get all module names registered with the current tennet
            var moduleNames = descriptor.Modules.Select(x => x.ModuleId).ToArray();

            // Get module entries for active modules
            var modules = await _moduleManager.LoadModulesAsync(moduleNames);

            //// Get all dependencies for loaded modules
            var entries = new Dictionary <Type, IModuleEntry>();

            if (modules != null)
            {
                foreach (var module in modules)
                {
                    var types = module.Assemblies.SelectMany(assembly =>
                                                             assembly.ExportedTypes.Where(IsComponentType));
                    foreach (var type in types)
                    {
                        if (!entries.ContainsKey(type))
                        {
                            entries.Add(type, module);
                        }
                    }
                }
            }

            var result = new ShellBlueprint
            {
                Settings     = settings,
                Descriptor   = descriptor,
                Dependencies = entries
            };

            if (_logger.IsEnabled(LogLevel.Debug))
            {
                _logger.LogDebug("Done composing blueprint");
            }
            return(result);
        }
Ejemplo n.º 17
0
 public SessionFactoryHolder(IHostEnvironment hostEnvironment, ISessionConfigurationCache sessionConfigurationCache,
                             IDatabaseCacheConfiguration cacheConfiguration,
                             ShellBlueprint shellBluePrint,
                             Func <IEnumerable <ISessionConfigurationEvents> > configurers,
                             ShellSettings shellSettings,
                             IAppDataFolder appDataFolder,
                             IDataServicesProviderFactory dataServicesProviderFactory)
 {
     Logger                       = NullLogger.Instance;
     _hostEnvironment             = hostEnvironment;
     _sessionConfigurationCache   = sessionConfigurationCache;
     _cacheConfiguration          = cacheConfiguration;
     _configurers                 = configurers;
     _dataServicesProviderFactory = dataServicesProviderFactory;
     _shellSettings               = shellSettings;
     _shellBlueprint              = shellBluePrint;
     _appDataFolder               = appDataFolder;
 }
        public SessionFactoryHolder(
            ShellSettings shellSettings,
            ShellBlueprint shellBlueprint,
            IDataServicesProviderFactory dataServicesProviderFactory,
            IAppDataFolder appDataFolder,
            ISessionConfigurationCache sessionConfigurationCache,
            IHostEnvironment hostEnvironment)
        {
            _shellSettings  = shellSettings;
            _shellBlueprint = shellBlueprint;
            _dataServicesProviderFactory = dataServicesProviderFactory;
            _appDataFolder             = appDataFolder;
            _sessionConfigurationCache = sessionConfigurationCache;
            _hostEnvironment           = hostEnvironment;

            T      = NullLocalizer.Instance;
            Logger = NullLogger.Instance;
        }
Ejemplo n.º 19
0
        public SessionConfigurationCache(IConfigurationService configurationService,
                                         ShellBlueprint shellBlueprint,
                                         IUserFolder userFolder)
        {
            ConfigurationService = configurationService;
            UserFolder           = userFolder;
            _shellBlueprint      = shellBlueprint;
            _currentConfig       = null;
            Logger = NullLogger.Instance;

            lock (syncRoot)
            {
                if (!HasBeenInitialized)
                {
                    DeleteCache();
                    HasBeenInitialized = true;
                }
            }
        }
        public AdminController(
            IOrchardServices orchardServices,
            IContentManager contentManager,
            IModuleGeneratorService moduleGeneratorService,
            IZipFileService zipFileService,
            ShellSettings shellSettings,
            ShellBlueprint shellBlueprint,
            IAppDataFolder appDataFolder)
        {
            _orchardServices        = orchardServices;
            _contentManager         = contentManager;
            _moduleGeneratorService = moduleGeneratorService;
            _zipFileService         = zipFileService;
            _shellSettings          = shellSettings;
            _shellBlueprint         = shellBlueprint;
            _appDataFolder          = appDataFolder;

            Logger = NullLogger.Instance;
            T      = NullLocalizer.Instance;
        }
Ejemplo n.º 21
0
        public async Task <ShellBlueprint> ComposeAsync(ShellSettings settings, ShellDescriptor descriptor)
        {
            if (_logger.IsEnabled(LogLevel.Debug))
            {
                _logger.LogDebug("Composing blueprint");
            }

            var enabledFeatures = descriptor
                                  .Features
                                  .SelectMany(shellFeature => _extensionManager.GetFeatureDependencies(shellFeature.Id))
                                  .Distinct()
                                  .ToArray();

            var features = await Task.WhenAll(enabledFeatures.Select(ef => _extensionManager.LoadFeatureAsync(ef)));

            // Statup classes are the only types that are automatically added to the blueprint
            var dependencies = BuildBlueprint(features, IsStartup, BuildModule, Enumerable.Empty <string>());

            var uniqueDependencies = new Dictionary <Type, DependencyBlueprint>();

            foreach (var dependency in dependencies)
            {
                if (!uniqueDependencies.ContainsKey(dependency.Type))
                {
                    uniqueDependencies.Add(dependency.Type, dependency);
                }
            }

            var result = new ShellBlueprint
            {
                Settings     = settings,
                Descriptor   = descriptor,
                Dependencies = uniqueDependencies.Values
            };

            if (_logger.IsEnabled(LogLevel.Debug))
            {
                _logger.LogDebug("Done composing blueprint");
            }
            return(result);
        }
 public SessionFactoryHolder(
     IConfigurationService configService,
     [Import(RequiredCreationPolicy = CreationPolicy.Shared)]
     IShellBlueprintFactory shellBlueprintFactory,
     IDataServicesProviderFactory dataServicesProviderFactory,
     IUserFolder userFolder,
     [Import(RequiredCreationPolicy = CreationPolicy.Shared)]
     ISessionConfigurationCache sessionConfigurationCache)
 {
     ConfigService    = configService;
     ShellBlueprint   = shellBlueprintFactory.CreateBlueprint();
     BluePrintFactory = () =>
     {
         shellBlueprintFactory.Reset();
         return(shellBlueprintFactory.CreateBlueprint());
     };
     _dataServicesProviderFactory = dataServicesProviderFactory;
     _userFolder = userFolder;
     _sessionConfigurationCache = sessionConfigurationCache;
     Logger = NullLogger.Instance;
 }
Ejemplo n.º 23
0
        public async Task <ShellBlueprint> ComposeAsync(ShellSettings settings, ShellDescriptor descriptor)
        {
            if (_logger.IsEnabled(LogLevel.Debug))
            {
                _logger.LogDebug("Composing blueprint");
            }

            var featureNames = descriptor.Features.Select(x => x.Id).ToArray();

            var features = await _extensionManager.LoadFeaturesAsync(featureNames);

            var entries = new Dictionary <Type, FeatureEntry>();

            foreach (var feature in features)
            {
                foreach (var exportedType in feature.ExportedTypes)
                {
                    var requiredFeatures = RequireFeaturesAttribute.GetRequiredFeatureNamesForType(exportedType);

                    if (requiredFeatures.All(x => featureNames.Contains(x)))
                    {
                        entries.Add(exportedType, feature);
                    }
                }
            }

            var result = new ShellBlueprint
            {
                Settings     = settings,
                Descriptor   = descriptor,
                Dependencies = entries
            };

            if (_logger.IsEnabled(LogLevel.Debug))
            {
                _logger.LogDebug("Done composing blueprint");
            }

            return(result);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// 组合外壳蓝图。
        /// </summary>
        /// <param name="settings">外壳设置。</param>
        /// <param name="descriptor">外壳描述符。</param>
        /// <returns>外壳蓝图。</returns>
        public ShellBlueprint Compose(ShellSettings settings, ShellDescriptor descriptor)
        {
            Logger.Debug("组合外壳蓝图");

            var enabledFeatures = _extensionManager.EnabledFeatures(descriptor);
            var features        = _extensionManager.LoadFeatures(enabledFeatures).ToArray();

            if (descriptor.Features.Any(feature => feature.Name == "SuperRocket.Framework"))
            {
                features = features.Concat(BuiltinFeatures()).ToArray();
            }

            var excludedTypes = GetExcludedTypes(features).ToArray();

            var modules      = BuildBlueprint(features, IsModule, BuildModule, excludedTypes);
            var dependencies = BuildBlueprint(features, IsDependency, BuildDependency, excludedTypes);

            var result = new ShellBlueprint
            {
                Settings     = settings,
                Descriptor   = descriptor,
                Dependencies = dependencies.Concat(modules).ToArray()
            };

            Logger.Debug("准备应用外部组合策略。");
            var context = new CompositionStrategyApplyContext
            {
                Features       = features,
                ExcludedTypes  = excludedTypes,
                ShellBlueprint = result
            };

            _compositionStrategyProviders.Invoke(i => i.Apply(context), Logger);
            Logger.Debug("应用外部组合策略成功。");

            Logger.Debug("组合外壳蓝图完成。");
            return(result);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// 注册动作。
        /// </summary>
        /// <param name="builder">容器建造者。</param>
        /// <param name="blueprint">外壳蓝图。</param>
        public void Registrations(ContainerBuilder builder, ShellBlueprint blueprint)
        {
            foreach (var item in blueprint.GetControllers())
            {
                var serviceKeyName = (item.AreaName + "/" + item.ControllerName).ToLowerInvariant();
                var serviceKeyType = item.Type;
                RegisterType(builder, item)
                .Keyed <IController>(serviceKeyName)
                .Keyed <IController>(serviceKeyType)
                .WithMetadata("ControllerType", item.Type)
                .InstancePerDependency();
            }

            foreach (var item in blueprint.GetHttpControllers())
            {
                var serviceKeyName = (item.AreaName + "/" + item.ControllerName).ToLowerInvariant();
                var serviceKeyType = item.Type;
                RegisterType(builder, item)
                .Keyed <IHttpController>(serviceKeyName)
                .Keyed <IHttpController>(serviceKeyType)
                .WithMetadata("ControllerType", item.Type)
                .InstancePerDependency();
            }
        }
Ejemplo n.º 26
0
        public ShellBlueprint Compose(ShellSettings settings, ShellDescriptor descriptor)
        {
            if (_logger.IsEnabled(LogLevel.Debug))
            {
                _logger.LogDebug("Composing blueprint");
            }

            var enabledFeatures = _extensionManager.EnabledFeatures(descriptor);
            var features        = _extensionManager.LoadFeatures(enabledFeatures);

            // Statup classes are the only types that are automatically added to the blueprint
            var dependencies = BuildBlueprint(features, IsStartup, BuildModule, Enumerable.Empty <string>());

            var uniqueDependencies = new Dictionary <Type, DependencyBlueprint>();

            foreach (var dependency in dependencies)
            {
                if (!uniqueDependencies.ContainsKey(dependency.Type))
                {
                    uniqueDependencies.Add(dependency.Type, dependency);
                }
            }

            var result = new ShellBlueprint
            {
                Settings     = settings,
                Descriptor   = descriptor,
                Dependencies = uniqueDependencies.Values
            };

            if (_logger.IsEnabled(LogLevel.Debug))
            {
                _logger.LogDebug("Done composing blueprint");
            }
            return(result);
        }
        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).AsSelf();
                        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()
                    ;
                }

                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 optionalShellByNameConfig = HostingEnvironment.MapPath("~/Config/Sites." + settings.Name + ".config");
                if (File.Exists(optionalShellByNameConfig))
                {
                    builder.RegisterModule(new ConfigurationSettingsReader(ConfigurationSettingsReaderConstants.DefaultSectionName, optionalShellByNameConfig));
                }
                else
                {
                    var optionalShellConfig = HostingEnvironment.MapPath("~/Config/Sites.config");
                    if (File.Exists(optionalShellConfig))
                    {
                        builder.RegisterModule(new ConfigurationSettingsReader(ConfigurationSettingsReaderConstants.DefaultSectionName, optionalShellConfig));
                    }
                }

                var optionalComponentsConfig = HostingEnvironment.MapPath("~/Config/HostComponents.config");
                if (File.Exists(optionalComponentsConfig))
                {
                    builder.RegisterModule(new HostComponentsConfigModule(optionalComponentsConfig));
                }
            }));
        }
Ejemplo n.º 28
0
        public IServiceProvider CreateContainer(ShellSettings settings, ShellBlueprint blueprint)
        {
            var featureByType = blueprint.Dependencies.ToDictionary(x => x.Type, x => x.Feature);
            IServiceCollection tenantServiceCollection = _serviceProvider.CreateChildContainer(_applicationServices);

            tenantServiceCollection.AddInstance(settings);
            tenantServiceCollection.AddInstance(blueprint.Descriptor);
            tenantServiceCollection.AddInstance(blueprint);

            // Sure this is right?
            tenantServiceCollection.AddInstance(_loggerFactory);

            foreach (var dependency in blueprint.Dependencies
                     .Where(t => !typeof(IModule).IsAssignableFrom(t.Type)))
            {
                foreach (var interfaceType in dependency.Type.GetInterfaces()
                         .Where(itf => typeof(IDependency).IsAssignableFrom(itf)))
                {
                    _logger.LogDebug("Type: {0}, Interface Type: {1}", dependency.Type, interfaceType);

                    if (typeof(ISingletonDependency).IsAssignableFrom(interfaceType))
                    {
                        tenantServiceCollection.AddSingleton(interfaceType, dependency.Type);
                    }
                    else if (typeof(IUnitOfWorkDependency).IsAssignableFrom(interfaceType))
                    {
                        tenantServiceCollection.AddScoped(interfaceType, dependency.Type);
                    }
                    else if (typeof(ITransientDependency).IsAssignableFrom(interfaceType))
                    {
                        tenantServiceCollection.AddTransient(interfaceType, dependency.Type);
                    }
                    else
                    {
                        tenantServiceCollection.AddScoped(interfaceType, dependency.Type);
                    }
                }
            }

            // Configure event handlers, they are not part of the blueprint, so they have
            // to be added manually. Or need to create a module for this.
            tenantServiceCollection.AddScoped <IEventBus, DefaultOrchardEventBus>();
            tenantServiceCollection.AddSingleton <IEventBusState, EventBusState>();

            // Configuring data access
            var indexes = blueprint
                          .Dependencies
                          .Where(x => typeof(IIndexProvider).IsAssignableFrom(x.Type))
                          .Select(x => x.Type).ToArray();

            if (settings.DatabaseProvider != null)
            {
                var store = new Store(cfg =>
                {
                    // @"Data Source =.; Initial Catalog = test1; User Id=sa;Password=demo123!"

                    IConnectionFactory connectionFactory = null;

                    switch (settings.DatabaseProvider)
                    {
                    case "SqlConnection":
                        connectionFactory = new DbConnectionFactory <SqlConnection>(settings.ConnectionString);
                        break;

                    //case "SqliteConnection":
                    //    connectionFactory = new DbConnectionFactory<SqliteConnection>(settings.ConnectionString);
                    //    break;
                    default:
                        throw new ArgumentException("Unkown database provider: " + settings.DatabaseProvider);
                    }

                    var sqlFactory = new SqlDocumentStorageFactory(connectionFactory);;

                    cfg.ConnectionFactory      = connectionFactory;
                    cfg.DocumentStorageFactory = sqlFactory;
                    cfg.IsolationLevel         = sqlFactory.IsolationLevel = IsolationLevel.ReadUncommitted;

                    if (!String.IsNullOrWhiteSpace(settings.TablePrefix))
                    {
                        cfg.TablePrefix = sqlFactory.TablePrefix = settings.TablePrefix + "_";
                    }

                    //cfg.RunDefaultMigration();
                }
                                      );

                var idGenerator = new LinearBlockIdGenerator(store.Configuration.ConnectionFactory, 20, "contentitem", store.Configuration.TablePrefix);

                store.RegisterIndexes(indexes);

                tenantServiceCollection.AddInstance <IStore>(store);
                tenantServiceCollection.AddInstance <LinearBlockIdGenerator>(idGenerator);

                tenantServiceCollection.AddScoped <ISession>(serviceProvider =>
                                                             store.CreateSession()
                                                             );
            }

            tenantServiceCollection.AddInstance <ITypeFeatureProvider>(new TypeFeatureProvider(featureByType));

            IServiceCollection moduleServiceCollection =
                _serviceProvider.CreateChildContainer(_applicationServices);

            foreach (var dependency in blueprint.Dependencies
                     .Where(t => typeof(IModule).IsAssignableFrom(t.Type)))
            {
                moduleServiceCollection.AddScoped(typeof(IModule), dependency.Type);
            }

            var moduleServiceProvider = moduleServiceCollection.BuildServiceProvider();

            // Let any module add custom service descriptors to the tenant
            foreach (var service in moduleServiceProvider.GetServices <IModule>())
            {
                service.Configure(tenantServiceCollection);
            }

            // Register event handlers on the event bus
            var eventHandlers = tenantServiceCollection
                                .Select(x => x.ImplementationType)
                                .Where(t => t != null && typeof(IEventHandler).IsAssignableFrom(t) && t.GetTypeInfo().IsClass)
                                .ToArray();

            foreach (var handlerClass in eventHandlers)
            {
                tenantServiceCollection.AddScoped(handlerClass);

                // Register dynamic proxies to intercept direct calls if an IEventHandler is resolved, dispatching the call to
                // the event bus.

                foreach (var i in handlerClass.GetInterfaces().Where(t => typeof(IEventHandler).IsAssignableFrom(t)))
                {
                    tenantServiceCollection.AddScoped(i, serviceProvider =>
                    {
                        var proxy      = DefaultOrchardEventBus.CreateProxy(i);
                        proxy.EventBus = serviceProvider.GetService <IEventBus>();
                        return(proxy);
                    });
                }
            }

            var shellServiceProvider = tenantServiceCollection.BuildServiceProvider();
            var eventBusState        = shellServiceProvider.GetService <IEventBusState>();

            // Register any IEventHandler method in the event bus
            foreach (var handlerClass in eventHandlers)
            {
                foreach (var handlerInterface in handlerClass.GetInterfaces().Where(x => typeof(IEventHandler).IsAssignableFrom(x)))
                {
                    foreach (var interfaceMethod in handlerInterface.GetMethods())
                    {
                        //var classMethod = handlerClass.GetMethods().Where(x => x.Name == interfaceMethod.Name && x.GetParameters().Length == interfaceMethod.GetParameters().Length).FirstOrDefault();
                        Func <IServiceProvider, IDictionary <string, object>, Task> d = (sp, parameters) => DefaultOrchardEventBus.Invoke(sp, parameters, interfaceMethod, handlerClass);
                        eventBusState.Add(handlerInterface.Name + "." + interfaceMethod.Name, d);
                    }
                }
            }

            return(shellServiceProvider);
        }
Ejemplo n.º 29
0
        public IServiceProvider CreateContainer(ShellSettings settings, ShellBlueprint blueprint)
        {
            var tenantServiceCollection = _serviceProvider.CreateChildContainer(_applicationServices);

            tenantServiceCollection.AddSingleton(settings);
            tenantServiceCollection.AddSingleton(blueprint.Descriptor);
            tenantServiceCollection.AddSingleton(blueprint);

            AddCoreServices(tenantServiceCollection);

            // Execute IStartup registrations

            // TODO: Use StartupLoader in RTM and then don't need to register the classes anymore then

            var moduleServiceCollection = _serviceProvider.CreateChildContainer(_applicationServices);

            foreach (var dependency in blueprint.Dependencies.Where(t => typeof(IStartup).IsAssignableFrom(t.Key)))
            {
                moduleServiceCollection.AddSingleton(typeof(IStartup), dependency.Key);
                tenantServiceCollection.AddSingleton(typeof(IStartup), dependency.Key);
            }

            // Add a default configuration if none has been provided
            var configuration = new ConfigurationBuilder().AddInMemoryCollection().Build();

            moduleServiceCollection.TryAddSingleton(configuration);
            tenantServiceCollection.TryAddSingleton(configuration);

            // Make shell settings available to the modules
            moduleServiceCollection.AddSingleton(settings);

            var moduleServiceProvider = moduleServiceCollection.BuildServiceProvider(true);

            // Index all service descriptors by their feature id
            var featureAwareServiceCollection = new FeatureAwareServiceCollection(tenantServiceCollection);

            var startups = moduleServiceProvider.GetServices <IStartup>();

            // IStartup instances are ordered by module dependency with an Order of 0 by default.
            // OrderBy performs a stable sort so order is preserved among equal Order values.
            startups = startups.OrderBy(s => s.Order);

            // Let any module add custom service descriptors to the tenant
            foreach (var startup in startups)
            {
                var feature = blueprint.Dependencies.FirstOrDefault(x => x.Key == startup.GetType()).Value?.FeatureInfo;

                // If the startup is not coming from an extension, associate it to the application feature.
                // For instance when Startup classes are registered with Configure<Startup>() from the application.

                featureAwareServiceCollection.SetCurrentFeature(feature ?? _applicationFeature);
                startup.ConfigureServices(featureAwareServiceCollection);
            }

            (moduleServiceProvider as IDisposable).Dispose();

            var shellServiceProvider = tenantServiceCollection.BuildServiceProvider(true);

            // Register all DIed types in ITypeFeatureProvider
            var typeFeatureProvider = shellServiceProvider.GetRequiredService <ITypeFeatureProvider>();

            foreach (var featureServiceCollection in featureAwareServiceCollection.FeatureCollections)
            {
                foreach (var serviceDescriptor in featureServiceCollection.Value)
                {
                    if (serviceDescriptor.ImplementationType != null)
                    {
                        typeFeatureProvider.TryAdd(serviceDescriptor.ImplementationType, featureServiceCollection.Key);
                    }
                    else if (serviceDescriptor.ImplementationInstance != null)
                    {
                        typeFeatureProvider.TryAdd(serviceDescriptor.ImplementationInstance.GetType(), featureServiceCollection.Key);
                    }
                    else
                    {
                        // Factory, we can't know which type will be returned
                    }
                }
            }

            return(shellServiceProvider);
        }
Ejemplo n.º 30
0
 public StandardExtensionRouteProvider(ShellBlueprint blueprint)
 {
     _blueprint = blueprint;
 }