more dependancy injection. still just beginning

This commit is contained in:
LukePulverenti 2013-02-22 22:49:00 -05:00
parent 57cb08085d
commit c165f37bb9
13 changed files with 147 additions and 206 deletions

View File

@ -18,7 +18,6 @@ using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using SimpleInjector;
namespace MediaBrowser.Common.Kernel
{
@ -223,12 +222,6 @@ namespace MediaBrowser.Common.Kernel
/// <value>The task manager.</value>
public TaskManager TaskManager { get; private set; }
/// <summary>
/// Gets the iso manager.
/// </summary>
/// <value>The iso manager.</value>
public IIsoManager IsoManager { get; private set; }
/// <summary>
/// Gets the rest services.
/// </summary>
@ -347,20 +340,14 @@ namespace MediaBrowser.Common.Kernel
/// Initializes a new instance of the <see cref="BaseKernel{TApplicationPathsType}" /> class.
/// </summary>
/// <param name="appHost">The app host.</param>
/// <param name="isoManager">The iso manager.</param>
/// <param name="logger">The logger.</param>
/// <exception cref="System.ArgumentNullException">isoManager</exception>
protected BaseKernel(IApplicationHost appHost, IIsoManager isoManager, ILogger logger)
protected BaseKernel(IApplicationHost appHost, ILogger logger)
{
if (appHost == null)
{
throw new ArgumentNullException("appHost");
}
if (isoManager == null)
{
throw new ArgumentNullException("isoManager");
}
if (logger == null)
{
@ -368,7 +355,6 @@ namespace MediaBrowser.Common.Kernel
}
ApplicationHost = appHost;
IsoManager = isoManager;
Logger = logger;
}
@ -471,11 +457,6 @@ namespace MediaBrowser.Common.Kernel
CompositionContainer.Catalog.Dispose();
}
/// <summary>
/// The ioc container
/// </summary>
private readonly Container _iocContainer = new Container();
/// <summary>
/// Composes the parts.
/// </summary>
@ -486,19 +467,18 @@ namespace MediaBrowser.Common.Kernel
CompositionContainer = GetSafeCompositionContainer(concreteTypes.Select(i => new TypeCatalog(i)));
ComposeExportedValues(CompositionContainer, _iocContainer);
RegisterExportedValues(CompositionContainer);
CompositionContainer.ComposeParts(this);
ComposePartsWithIocContainer(concreteTypes, _iocContainer);
FindParts(concreteTypes);
}
/// <summary>
/// Composes the parts with ioc container.
/// </summary>
/// <param name="allTypes">All types.</param>
/// <param name="container">The container.</param>
protected virtual void ComposePartsWithIocContainer(Type[] allTypes, Container container)
protected virtual void FindParts(Type[] allTypes)
{
RestServices = GetExports<IRestfulService>(allTypes);
WebSocketListeners = GetExports<IWebSocketListener>(allTypes);
@ -530,21 +510,20 @@ namespace MediaBrowser.Common.Kernel
/// <returns>System.Object.</returns>
private object Instantiate(Type type)
{
return _iocContainer.GetInstance(type);
return ApplicationHost.CreateInstance(type);
}
/// <summary>
/// Composes the exported values.
/// </summary>
/// <param name="container">The container.</param>
/// <param name="iocContainer"></param>
protected virtual void ComposeExportedValues(CompositionContainer container, Container iocContainer)
protected virtual void RegisterExportedValues(CompositionContainer container)
{
ApplicationHost.Register<IKernel>(this);
container.ComposeExportedValue("logger", Logger);
container.ComposeExportedValue("appHost", ApplicationHost);
iocContainer.RegisterSingle(Logger);
iocContainer.RegisterSingle(ApplicationHost);
container.ComposeExportedValue("isoManager", ApplicationHost.Resolve<IIsoManager>());
}
/// <summary>
@ -739,7 +718,6 @@ namespace MediaBrowser.Common.Kernel
{
DisposeTcpManager();
DisposeTaskManager();
DisposeIsoManager();
DisposeHttpManager();
DisposeComposableParts();
@ -753,18 +731,6 @@ namespace MediaBrowser.Common.Kernel
}
}
/// <summary>
/// Disposes the iso manager.
/// </summary>
private void DisposeIsoManager()
{
if (IsoManager != null)
{
IsoManager.Dispose();
IsoManager = null;
}
}
/// <summary>
/// Disposes the TCP manager.
/// </summary>

View File

@ -43,5 +43,26 @@ namespace MediaBrowser.Common.Kernel
/// </summary>
/// <returns>Task.</returns>
Task UpdateApplication(CancellationToken cancellationToken, IProgress<double> progress);
/// <summary>
/// Creates an instance of type and resolves all constructor dependancies
/// </summary>
/// <param name="type">The type.</param>
/// <returns>System.Object.</returns>
object CreateInstance(Type type);
/// <summary>
/// Registers a service that other classes can use as a dependancy.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj">The obj.</param>
void Register<T>(T obj) where T : class;
/// <summary>
/// Resolves this instance.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns>``0.</returns>
T Resolve<T>() where T : class;
}
}

View File

@ -88,9 +88,6 @@
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\ServiceStack.Text.3.9.37\lib\net35\ServiceStack.Text.dll</HintPath>
</Reference>
<Reference Include="SimpleInjector">
<HintPath>..\packages\SimpleInjector.2.0.0-beta5\lib\net40-client\SimpleInjector.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.ComponentModel.Composition" />
<Reference Include="System.Configuration" />

View File

@ -13,5 +13,4 @@
<package id="ServiceStack.OrmLite.SqlServer" version="3.9.37" targetFramework="net45" />
<package id="ServiceStack.Redis" version="3.9.37" targetFramework="net45" />
<package id="ServiceStack.Text" version="3.9.37" targetFramework="net45" />
<package id="SimpleInjector" version="2.0.0-beta5" targetFramework="net45" />
</packages>

View File

@ -28,7 +28,6 @@ using System.ComponentModel.Composition.Hosting;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using SimpleInjector;
namespace MediaBrowser.Controller
{
@ -301,48 +300,16 @@ namespace MediaBrowser.Controller
get { return 7359; }
}
/// <summary>
/// Gets or sets the zip client.
/// </summary>
/// <value>The zip client.</value>
private IZipClient ZipClient { get; set; }
/// <summary>
/// Gets or sets the bluray examiner.
/// </summary>
/// <value>The bluray examiner.</value>
private IBlurayExaminer BlurayExaminer { get; set; }
/// <summary>
/// Creates a kernel based on a Data path, which is akin to our current programdata path
/// </summary>
/// <param name="appHost">The app host.</param>
/// <param name="isoManager">The iso manager.</param>
/// <param name="zipClient">The zip client.</param>
/// <param name="blurayExaminer">The bluray examiner.</param>
/// <param name="logger">The logger.</param>
/// <exception cref="System.ArgumentNullException">isoManager</exception>
public Kernel(IApplicationHost appHost, IIsoManager isoManager, IZipClient zipClient, IBlurayExaminer blurayExaminer, ILogger logger)
: base(appHost, isoManager, logger)
public Kernel(IApplicationHost appHost, ILogger logger)
: base(appHost, logger)
{
if (isoManager == null)
{
throw new ArgumentNullException("isoManager");
}
if (zipClient == null)
{
throw new ArgumentNullException("zipClient");
}
if (blurayExaminer == null)
{
throw new ArgumentNullException("blurayExaminer");
}
Instance = this;
ZipClient = zipClient;
BlurayExaminer = blurayExaminer;
// For now there's no real way to inject this properly
BaseItem.Logger = logger;
@ -356,26 +323,22 @@ namespace MediaBrowser.Controller
/// Composes the exported values.
/// </summary>
/// <param name="container">The container.</param>
/// <param name="iocContainer">The _ioc container.</param>
protected override void ComposeExportedValues(CompositionContainer container, Container iocContainer)
protected override void RegisterExportedValues(CompositionContainer container)
{
base.ComposeExportedValues(container, iocContainer);
container.ComposeExportedValue("kernel", this);
container.ComposeExportedValue("blurayExaminer", BlurayExaminer);
iocContainer.RegisterSingle(this);
iocContainer.RegisterSingle(BlurayExaminer);
ApplicationHost.Register(this);
base.RegisterExportedValues(container);
}
/// <summary>
/// Composes the parts with ioc container.
/// </summary>
/// <param name="allTypes">All types.</param>
/// <param name="container">The container.</param>
protected override void ComposePartsWithIocContainer(Type[] allTypes, Container container)
protected override void FindParts(Type[] allTypes)
{
base.ComposePartsWithIocContainer(allTypes, container);
base.FindParts(allTypes);
EntityResolutionIgnoreRules = GetExports<IResolutionIgnoreRule>(allTypes);
UserDataRepositories = GetExports<IUserDataRepository>(allTypes);
@ -395,24 +358,22 @@ namespace MediaBrowser.Controller
/// <returns>Task.</returns>
protected override async Task ReloadInternal()
{
Logger.Info("Extracting tools");
// Reset these so that they can be lazy loaded again
Users = null;
RootFolder = null;
ReloadResourcePools();
InstallationManager = new InstallationManager(this, ZipClient, Logger);
LibraryManager = new LibraryManager(this, Logger);
UserManager = new UserManager(this, Logger);
FFMpegManager = new FFMpegManager(this, ZipClient, Logger);
ImageManager = new ImageManager(this, Logger);
ProviderManager = new ProviderManager(this, Logger);
UserDataManager = new UserDataManager(this, Logger);
PluginSecurityManager = new PluginSecurityManager(this);
await base.ReloadInternal().ConfigureAwait(false);
ReloadResourcePools();
InstallationManager = (InstallationManager)ApplicationHost.CreateInstance(typeof(InstallationManager));
FFMpegManager = (FFMpegManager)ApplicationHost.CreateInstance(typeof(FFMpegManager));
LibraryManager = (LibraryManager)ApplicationHost.CreateInstance(typeof(LibraryManager));
UserManager = (UserManager)ApplicationHost.CreateInstance(typeof(UserManager));
ImageManager = (ImageManager)ApplicationHost.CreateInstance(typeof(ImageManager));
ProviderManager = (ProviderManager)ApplicationHost.CreateInstance(typeof(ProviderManager));
UserDataManager = (UserDataManager)ApplicationHost.CreateInstance(typeof(UserDataManager));
PluginSecurityManager = (PluginSecurityManager)ApplicationHost.CreateInstance(typeof(PluginSecurityManager));
ReloadFileSystemManager();
await UserManager.RefreshUsersMetadata(CancellationToken.None).ConfigureAwait(false);

View File

@ -63,10 +63,6 @@
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\protobuf-net.2.0.0.621\lib\net40\protobuf-net.dll</HintPath>
</Reference>
<Reference Include="SimpleInjector, Version=2.0.0.0, Culture=neutral, PublicKeyToken=984cb50dea722e99, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\SimpleInjector.2.0.0-beta5\lib\net40-client\SimpleInjector.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.ComponentModel.Composition" />
<Reference Include="System.Core" />

View File

@ -4,9 +4,9 @@ using MediaBrowser.Common.Kernel;
using MediaBrowser.Common.Serialization;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@ -17,7 +17,6 @@ using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Model.Logging;
namespace MediaBrowser.Controller.MediaInfo
{
@ -26,22 +25,6 @@ namespace MediaBrowser.Controller.MediaInfo
/// </summary>
public class FFMpegManager : BaseManager<Kernel>
{
/// <summary>
/// Holds the list of new items to generate chapter image for when the NewItemTimer expires
/// </summary>
private readonly List<Video> _newlyAddedItems = new List<Video>();
/// <summary>
/// The amount of time to wait before generating chapter images
/// </summary>
private const int NewItemDelay = 300000;
/// <summary>
/// The current new item timer
/// </summary>
/// <value>The new item timer.</value>
private Timer NewItemTimer { get; set; }
/// <summary>
/// Gets or sets the video image cache.
/// </summary>
@ -96,73 +79,9 @@ namespace MediaBrowser.Controller.MediaInfo
AudioImageCache = new FileSystemRepository(AudioImagesDataPath);
SubtitleCache = new FileSystemRepository(SubtitleCachePath);
Kernel.LibraryManager.LibraryChanged += LibraryManager_LibraryChanged;
Task.Run(() => VersionedDirectoryPath = GetVersionedDirectoryPath());
}
/// <summary>
/// Handles the LibraryChanged event of the LibraryManager control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="ChildrenChangedEventArgs" /> instance containing the event data.</param>
void LibraryManager_LibraryChanged(object sender, ChildrenChangedEventArgs e)
{
var videos = e.ItemsAdded.OfType<Video>().ToList();
// Use a timer to prevent lots of these notifications from showing in a short period of time
if (videos.Count > 0)
{
lock (_newlyAddedItems)
{
_newlyAddedItems.AddRange(videos);
if (NewItemTimer == null)
{
NewItemTimer = new Timer(NewItemTimerCallback, null, NewItemDelay, Timeout.Infinite);
}
else
{
NewItemTimer.Change(NewItemDelay, Timeout.Infinite);
}
}
}
}
/// <summary>
/// Called when the new item timer expires
/// </summary>
/// <param name="state">The state.</param>
private async void NewItemTimerCallback(object state)
{
List<Video> newItems;
// Lock the list and release all resources
lock (_newlyAddedItems)
{
newItems = _newlyAddedItems.ToList();
_newlyAddedItems.Clear();
NewItemTimer.Dispose();
NewItemTimer = null;
}
// Limit the number of videos we generate images for
// The idea is to catch new items that are added here and there
// Mass image generation can be left to the scheduled task
foreach (var video in newItems.Where(c => c.Chapters != null).Take(3))
{
try
{
await PopulateChapterImages(video, CancellationToken.None, true, true).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.ErrorException("Error creating chapter images for {0}", ex, video.Name);
}
}
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
@ -171,15 +90,8 @@ namespace MediaBrowser.Controller.MediaInfo
{
if (dispose)
{
if (NewItemTimer != null)
{
NewItemTimer.Dispose();
}
SetErrorMode(ErrorModes.SYSTEM_DEFAULT);
Kernel.LibraryManager.LibraryChanged -= LibraryManager_LibraryChanged;
AudioImageCache.Dispose();
VideoImageCache.Dispose();
}

View File

@ -14,6 +14,21 @@ namespace MediaBrowser.Controller.Providers.MediaInfo
[Export(typeof(BaseMetadataProvider))]
public class FFMpegVideoImageProvider : BaseFFMpegImageProvider<Video>
{
/// <summary>
/// The _iso manager
/// </summary>
private readonly IIsoManager _isoManager;
/// <summary>
/// Initializes a new instance of the <see cref="FFMpegVideoImageProvider" /> class.
/// </summary>
/// <param name="isoManager">The iso manager.</param>
[ImportingConstructor]
public FFMpegVideoImageProvider([Import("isoManager")] IIsoManager isoManager)
{
_isoManager = isoManager;
}
/// <summary>
/// Supportses the specified item.
/// </summary>
@ -30,7 +45,7 @@ namespace MediaBrowser.Controller.Providers.MediaInfo
if (video != null)
{
if (video.VideoType == VideoType.Iso && video.IsoType.HasValue && Kernel.Instance.IsoManager.CanMount(item.Path))
if (video.VideoType == VideoType.Iso && video.IsoType.HasValue && _isoManager.CanMount(item.Path))
{
return true;
}
@ -82,7 +97,7 @@ namespace MediaBrowser.Controller.Providers.MediaInfo
{
if (item.VideoType == VideoType.Iso)
{
return Kernel.Instance.IsoManager.Mount(item.Path, cancellationToken);
return _isoManager.Mount(item.Path, cancellationToken);
}
return NullMountTaskResult;

View File

@ -32,13 +32,19 @@ namespace MediaBrowser.Controller.Providers.MediaInfo
/// <value>The bluray examiner.</value>
private IBlurayExaminer BlurayExaminer { get; set; }
/// <summary>
/// The _iso manager
/// </summary>
private readonly IIsoManager _isoManager;
/// <summary>
/// Initializes a new instance of the <see cref="FFProbeVideoInfoProvider" /> class.
/// </summary>
/// <param name="isoManager">The iso manager.</param>
/// <param name="blurayExaminer">The bluray examiner.</param>
/// <exception cref="System.ArgumentNullException">blurayExaminer</exception>
[ImportingConstructor]
public FFProbeVideoInfoProvider([Import("blurayExaminer")] IBlurayExaminer blurayExaminer)
public FFProbeVideoInfoProvider([Import("isoManager")] IIsoManager isoManager, [Import("blurayExaminer")] IBlurayExaminer blurayExaminer)
: base()
{
if (blurayExaminer == null)
@ -47,6 +53,7 @@ namespace MediaBrowser.Controller.Providers.MediaInfo
}
BlurayExaminer = blurayExaminer;
_isoManager = isoManager;
BdInfoCache = new FileSystemRepository(Path.Combine(Kernel.Instance.ApplicationPaths.CachePath, "bdinfo"));
}
@ -76,7 +83,7 @@ namespace MediaBrowser.Controller.Providers.MediaInfo
{
if (video.VideoType == VideoType.Iso)
{
return Kernel.Instance.IsoManager.CanMount(item.Path);
return _isoManager.CanMount(item.Path);
}
return video.VideoType == VideoType.VideoFile || video.VideoType == VideoType.Dvd || video.VideoType == VideoType.BluRay;
@ -101,7 +108,7 @@ namespace MediaBrowser.Controller.Providers.MediaInfo
{
PopulateDvdStreamFiles(item, mount);
}
base.OnPreFetch(item, mount);
}
@ -115,7 +122,7 @@ namespace MediaBrowser.Controller.Providers.MediaInfo
{
if (item.VideoType == VideoType.Iso)
{
return Kernel.Instance.IsoManager.Mount(item.Path, cancellationToken);
return _isoManager.Mount(item.Path, cancellationToken);
}
return base.MountIsoIfNeeded(item, cancellationToken);

View File

@ -2,5 +2,4 @@
<packages>
<package id="morelinq" version="1.0.15631-beta" targetFramework="net45" />
<package id="protobuf-net" version="2.0.0.621" targetFramework="net45" />
<package id="SimpleInjector" version="2.0.0-beta5" targetFramework="net45" />
</packages>

View File

@ -1,9 +1,12 @@
using MediaBrowser.ClickOnce;
using MediaBrowser.Common.IO;
using MediaBrowser.Common.Kernel;
using MediaBrowser.Controller;
using MediaBrowser.IsoMounter;
using MediaBrowser.Logging.Nlog;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.MediaInfo;
using MediaBrowser.Model.Updates;
using MediaBrowser.Server.Uninstall;
using MediaBrowser.ServerApplication.Implementations;
@ -19,6 +22,7 @@ using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using SimpleInjector;
namespace MediaBrowser.ServerApplication
{
@ -73,6 +77,11 @@ namespace MediaBrowser.ServerApplication
/// <value>The log file path.</value>
public string LogFilePath { get; private set; }
/// <summary>
/// The container
/// </summary>
private Container _container = new Container();
/// <summary>
/// Initializes a new instance of the <see cref="App" /> class.
/// </summary>
@ -172,12 +181,26 @@ namespace MediaBrowser.ServerApplication
Shutdown();
}
/// <summary>
/// Registers resources that classes will depend on
/// </summary>
private void RegisterResources()
{
Register(this);
Register(Logger);
Register<IIsoManager>(new PismoIsoManager(Logger));
Register<IBlurayExaminer>(new BdInfoExaminer());
Register<IZipClient>(new DotNetZipClient());
}
/// <summary>
/// Loads the kernel.
/// </summary>
protected async void LoadKernel()
{
Kernel = new Kernel(this, new PismoIsoManager(Logger), new DotNetZipClient(), new BdInfoExaminer(), Logger);
RegisterResources();
Kernel = new Kernel(this, Logger);
try
{
@ -378,7 +401,7 @@ namespace MediaBrowser.ServerApplication
NlogManager.AddFileTarget(LogFilePath, Kernel.Configuration.EnableDebugLevelLogging);
}
/// <summary>
/// Gets the image.
/// </summary>
@ -485,5 +508,45 @@ namespace MediaBrowser.ServerApplication
{
return new ApplicationUpdater().UpdateApplication(cancellationToken, progress);
}
/// <summary>
/// Creates an instance of type and resolves all constructor dependancies
/// </summary>
/// <param name="type">The type.</param>
/// <returns>System.Object.</returns>
public object CreateInstance(Type type)
{
try
{
return _container.GetInstance(type);
}
catch
{
Logger.Error("Error creating {0}", type.Name);
throw;
}
}
/// <summary>
/// Registers the specified obj.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj">The obj.</param>
public void Register<T>(T obj)
where T : class
{
_container.RegisterSingle(obj);
}
/// <summary>
/// Resolves this instance.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns>``0.</returns>
public T Resolve<T>() where T : class
{
return (T)_container.GetRegistration(typeof (T), true).GetInstance();
}
}
}

View File

@ -128,6 +128,10 @@
<SpecificVersion>False</SpecificVersion>
<HintPath>..\ThirdParty\UPnP\Libs\Platinum.Managed.dll</HintPath>
</Reference>
<Reference Include="SimpleInjector, Version=2.0.0.0, Culture=neutral, PublicKeyToken=984cb50dea722e99, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\SimpleInjector.2.0.0-beta5\lib\net40-client\SimpleInjector.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Data" />

View File

@ -3,5 +3,6 @@
<package id="DotNetZip" version="1.9.1.8" targetFramework="net45" />
<package id="Hardcodet.Wpf.TaskbarNotification" version="1.0.4.0" targetFramework="net45" />
<package id="NLog" version="2.0.0.2000" targetFramework="net45" />
<package id="SimpleInjector" version="2.0.0-beta5" targetFramework="net45" />
<package id="System.Data.SQLite" version="1.0.84.0" targetFramework="net45" />
</packages>