Rename DependencyInjection into DI, cleanup components, compose

This commit is contained in:
Stephan
2016-10-07 14:34:55 +02:00
parent 172ae81924
commit a00ee8d275
232 changed files with 1119 additions and 589 deletions

View File

@@ -15,7 +15,7 @@ using LightInject;
using Umbraco.Core;
using Umbraco.Core.Components;
using Umbraco.Core.Configuration;
using Umbraco.Core.DependencyInjection;
using Umbraco.Core.DI;
using Umbraco.Core.Dictionary;
using Umbraco.Core.Events;
using Umbraco.Core.Logging;
@@ -25,9 +25,6 @@ using Umbraco.Core.Profiling;
using Umbraco.Core.PropertyEditors;
using Umbraco.Core.PropertyEditors.ValueConverters;
using Umbraco.Core.Services;
using Umbraco.Core.Services.Changes;
using Umbraco.Core.Sync;
using Umbraco.Web.Cache;
using Umbraco.Web.DependencyInjection;
using Umbraco.Web.Dictionary;
using Umbraco.Web.Editors;
@@ -44,98 +41,89 @@ using Umbraco.Web.UI.JavaScript;
using Umbraco.Web.WebApi;
using Umbraco.Web._Legacy.Actions;
using UmbracoExamine;
using Action = System.Action;
namespace Umbraco.Web
{
[RequireComponent(typeof(CoreRuntimeComponent))]
public class WebRuntimeComponent : UmbracoComponentBase, IRuntimeComponent
{
public override void Compose(ServiceContainer container, RuntimeLevel runtimeLevel)
public override void Compose(Composition composition)
{
base.Compose(container);
base.Compose(composition);
container.RegisterFrom<WebModelMappersCompositionRoot>();
composition.Container.RegisterFrom<WebModelMappersCompositionRoot>();
var pluginManager = container.GetInstance<PluginManager>();
var logger = container.GetInstance<ILogger>();
var proflog = container.GetInstance<ProfilingLogger>();
var pluginManager = composition.Container.GetInstance<PluginManager>();
var logger = composition.Container.GetInstance<ILogger>();
var proflog = composition.Container.GetInstance<ProfilingLogger>();
// register the http context and umbraco context accessors
// we *should* use the HttpContextUmbracoContextAccessor, however there are cases when
// we have no http context, eg when booting Umbraco or in background threads, so instead
// let's use an hybrid accessor that can fall back to a ThreadStatic context.
container.RegisterSingleton<IUmbracoContextAccessor, HybridUmbracoContextAccessor>();
composition.Container.RegisterSingleton<IUmbracoContextAccessor, HybridUmbracoContextAccessor>();
// register the 'current' umbraco context - transient - for eg controllers
container.Register(factory => factory.GetInstance<IUmbracoContextAccessor>().UmbracoContext);
composition.Container.Register(factory => factory.GetInstance<IUmbracoContextAccessor>().UmbracoContext);
// register a per-request HttpContextBase object
// is per-request so only one wrapper is created per request
container.Register<HttpContextBase>(factory => new HttpContextWrapper(factory.GetInstance<IHttpContextAccessor>().HttpContext), new PerRequestLifeTime());
composition.Container.Register<HttpContextBase>(factory => new HttpContextWrapper(factory.GetInstance<IHttpContextAccessor>().HttpContext), new PerRequestLifeTime());
// register the facade accessor - the "current" facade is in the umbraco context
container.RegisterSingleton<IFacadeAccessor, UmbracoContextFacadeAccessor>();
composition.Container.RegisterSingleton<IFacadeAccessor, UmbracoContextFacadeAccessor>();
// register a per-request UmbracoContext object
// no real need to be per request but assuming it is faster
container.Register(factory => factory.GetInstance<IUmbracoContextAccessor>().UmbracoContext, new PerRequestLifeTime());
composition.Container.Register(factory => factory.GetInstance<IUmbracoContextAccessor>().UmbracoContext, new PerRequestLifeTime());
// register the umbraco helper
// fixme - FUCK! how can this even work, it's not a singleton!
container.RegisterSingleton<UmbracoHelper>();
composition.Container.RegisterSingleton<UmbracoHelper>();
// replace some services
container.RegisterSingleton<IEventMessagesFactory, DefaultEventMessagesFactory>();
container.RegisterSingleton<IEventMessagesAccessor, HybridEventMessagesAccessor>();
container.RegisterSingleton<IApplicationTreeService, ApplicationTreeService>();
container.RegisterSingleton<ISectionService, SectionService>();
composition.Container.RegisterSingleton<IEventMessagesFactory, DefaultEventMessagesFactory>();
composition.Container.RegisterSingleton<IEventMessagesAccessor, HybridEventMessagesAccessor>();
composition.Container.RegisterSingleton<IApplicationTreeService, ApplicationTreeService>();
composition.Container.RegisterSingleton<ISectionService, SectionService>();
container.RegisterSingleton<IExamineIndexCollectionAccessor, ExamineIndexCollectionAccessor>();
composition.Container.RegisterSingleton<IExamineIndexCollectionAccessor, ExamineIndexCollectionAccessor>();
// IoC setup for LightInject for MVC/WebApi
// see comments on MixedScopeManagerProvider for explainations of what we are doing here
var smp = container.ScopeManagerProvider as MixedScopeManagerProvider;
var smp = composition.Container.ScopeManagerProvider as MixedScopeManagerProvider;
if (smp == null) throw new Exception("Container.ScopeManagerProvider is not MixedScopeManagerProvider.");
container.EnableMvc(); // does container.EnablePerWebRequestScope()
container.ScopeManagerProvider = smp; // reverts - we will do it last (in WebRuntime)
composition.Container.EnableMvc(); // does container.EnablePerWebRequestScope()
composition.Container.ScopeManagerProvider = smp; // reverts - we will do it last (in WebRuntime)
container.RegisterMvcControllers(pluginManager, GetType().Assembly);
container.EnableWebApi(GlobalConfiguration.Configuration);
container.RegisterApiControllers(pluginManager, GetType().Assembly);
composition.Container.RegisterMvcControllers(pluginManager, GetType().Assembly);
composition.Container.EnableWebApi(GlobalConfiguration.Configuration);
composition.Container.RegisterApiControllers(pluginManager, GetType().Assembly);
XsltExtensionCollectionBuilder.Register(container)
XsltExtensionCollectionBuilder.Register(composition.Container)
.AddExtensionObjectProducer(() => pluginManager.ResolveXsltExtensions());
EditorValidatorCollectionBuilder.Register(container)
composition.Container.RegisterCollectionBuilder<EditorValidatorCollectionBuilder>()
.Add(() => pluginManager.ResolveTypes<IEditorValidator>());
// set the default RenderMvcController
Current.DefaultRenderMvcControllerType = typeof(RenderMvcController); // fixme WRONG!
// override the default server messenger, we need to check if the legacy dist calls is enabled, if that is the
// case, then we'll set the default messenger to be the old one, otherwise we'll set it to the db messenger
// which will always be on.
if (UmbracoConfig.For.UmbracoSettings().DistributedCall.Enabled)
ComposeLegacyMessenger(container, runtimeLevel, logger);
else
ComposeMessenger(container, logger, proflog);
ActionCollectionBuilder.Register(container)
ActionCollectionBuilder.Register(composition.Container)
.SetProducer(() => pluginManager.ResolveActions());
var surfaceControllerTypes = new SurfaceControllerTypeCollection(pluginManager.ResolveSurfaceControllers());
container.RegisterInstance(surfaceControllerTypes);
composition.Container.RegisterInstance(surfaceControllerTypes);
var umbracoApiControllerTypes = new UmbracoApiControllerTypeCollection(pluginManager.ResolveUmbracoApiControllers());
container.RegisterInstance(umbracoApiControllerTypes);
composition.Container.RegisterInstance(umbracoApiControllerTypes);
// both TinyMceValueConverter (in Core) and RteMacroRenderingValueConverter (in Web) will be
// discovered when CoreBootManager configures the converters. We HAVE to remove one of them
// here because there cannot be two converters for one property editor - and we want the full
// RteMacroRenderingValueConverter that converts macros, etc. So remove TinyMceValueConverter.
// (the limited one, defined in Core, is there for tests) - same for others
container.GetInstance<PropertyValueConverterCollectionBuilder>()
composition.Container.GetInstance<PropertyValueConverterCollectionBuilder>()
.Remove<TinyMceValueConverter>()
.Remove<TextStringValueConverter>()
.Remove<MarkdownEditorValueConverter>()
@@ -143,17 +131,17 @@ namespace Umbraco.Web
// add all known factories, devs can then modify this list on application
// startup either by binding to events or in their own global.asax
FilteredControllerFactoryCollectionBuilder.Register(container)
composition.Container.RegisterCollectionBuilder<FilteredControllerFactoryCollectionBuilder>()
.Append<RenderControllerFactory>();
UrlProviderCollectionBuilder.Register(container)
composition.Container.RegisterCollectionBuilder < UrlProviderCollectionBuilder>()
//.Append<AliasUrlProvider>() // not enabled by default
.Append<DefaultUrlProvider>()
.Append<CustomRouteUrlProvider>();
container.RegisterSingleton<IContentLastChanceFinder, ContentFinderByLegacy404>();
composition.Container.RegisterSingleton<IContentLastChanceFinder, ContentFinderByLegacy404>();
ContentFinderCollectionBuilder.Register(container)
composition.Container.RegisterCollectionBuilder < ContentFinderCollectionBuilder>()
// all built-in finders in the correct order,
// devs can then modify this list on application startup
.Append<ContentFinderByPageIdQuery>()
@@ -164,89 +152,22 @@ namespace Umbraco.Web
.Append<ContentFinderByUrlAlias>()
.Append<ContentFinderByRedirectUrl>();
container.RegisterSingleton<ISiteDomainHelper, SiteDomainHelper>();
composition.Container.RegisterSingleton<ISiteDomainHelper, SiteDomainHelper>();
ThumbnailProviderCollectionBuilder.Register(container)
composition.Container.RegisterCollectionBuilder<ThumbnailProviderCollectionBuilder>()
.Add(pluginManager.ResolveThumbnailProviders());
ImageUrlProviderCollectionBuilder.Register(container)
composition.Container.RegisterCollectionBuilder<ImageUrlProviderCollectionBuilder>()
.Append(pluginManager.ResolveImageUrlProviders());
container.RegisterSingleton<ICultureDictionaryFactory, DefaultCultureDictionaryFactory>();
composition.Container.RegisterSingleton<ICultureDictionaryFactory, DefaultCultureDictionaryFactory>();
// register *all* checks, except those marked [HideFromTypeFinder] of course
HealthCheckCollectionBuilder.Register(container)
composition.Container.RegisterCollectionBuilder<HealthCheckCollectionBuilder>()
.Add(() => pluginManager.ResolveTypes<HealthCheck.HealthCheck>());
// auto-register views
container.RegisterAuto(typeof(UmbracoViewPage<>));
}
private static void ComposeLegacyMessenger(IServiceRegistry container, RuntimeLevel runtimeLevel, ILogger logger)
{
//set the legacy one by default - this maintains backwards compat
container.Register<IServerMessenger>(factory =>
{
var userService = factory.GetInstance<IUserService>();
return new BatchedWebServiceServerMessenger(() =>
{
// we should not proceed to change this if the app/database is not configured since there will
// be no user, plus we don't need to have server messages sent if this is the case.
if (runtimeLevel == RuntimeLevel.Run)
{
try
{
var user = userService.GetUserById(UmbracoConfig.For.UmbracoSettings().DistributedCall.UserId);
return Tuple.Create(user.Username, user.RawPasswordValue);
}
catch (Exception e)
{
logger.Error<WebRuntime>("An error occurred trying to set the IServerMessenger during application startup", e);
return null;
}
}
logger.Warn<WebRuntime>("Could not initialize the DefaultServerMessenger, the application is not configured or the database is not configured");
return null;
});
}, new PerContainerLifetime());
}
private static void ComposeMessenger(IServiceRegistry container, ILogger logger, ProfilingLogger proflog)
{
container.Register<IServerMessenger>(factory =>
{
var runtime = factory.GetInstance<IRuntimeState>();
var databaseContext = factory.GetInstance<DatabaseContext>();
return new BatchedDatabaseServerMessenger(
runtime, databaseContext, logger, proflog,
true,
//Default options for web including the required callbacks to build caches
new DatabaseServerMessengerOptions
{
//These callbacks will be executed if the server has not been synced
// (i.e. it is a new server or the lastsynced.txt file has been removed)
InitializingCallbacks = new Action[]
{
//rebuild the xml cache file if the server is not synced
() =>
{
// rebuild the facade caches entirely, if the server is not synced
// this is equivalent to DistributedCache RefreshAllFacade but local only
// (we really should have a way to reuse RefreshAllFacade... locally)
// note: refresh all content & media caches does refresh content types too
var svc = Current.FacadeService;
bool ignored1, ignored2;
svc.Notify(new[] { new DomainCacheRefresher.JsonPayload(0, DomainChangeTypes.RefreshAll) });
svc.Notify(new[] { new ContentCacheRefresher.JsonPayload(0, TreeChangeTypes.RefreshAll) }, out ignored1, out ignored2);
svc.Notify(new[] { new MediaCacheRefresher.JsonPayload(0, TreeChangeTypes.RefreshAll) }, out ignored1);
},
//rebuild indexes if the server is not synced
// NOTE: This will rebuild ALL indexes including the members, if developers want to target specific
// indexes then they can adjust this logic themselves.
() => RebuildIndexes(false)
}
});
}, new PerContainerLifetime());
composition.Container.RegisterAuto(typeof(UmbracoViewPage<>));
}
internal void Initialize(
@@ -317,9 +238,10 @@ namespace Umbraco.Web
GlobalConfiguration.Configuration.EnsureInitialized();
}
// fixme - this should move to something else, we should not depend on Examine here!
private static void RebuildIndexes(bool onlyEmptyIndexes)
{
var indexers = (IEnumerable<KeyValuePair<string, IExamineIndexer>>) ExamineManager.Instance.IndexProviders;
var indexers = (IEnumerable<KeyValuePair<string, IExamineIndexer>>)ExamineManager.Instance.IndexProviders;
if (onlyEmptyIndexes)
indexers = indexers.Where(x => x.Value.IsIndexNew());
foreach (var indexer in indexers)