rename and make it a non-static class

This commit is contained in:
Gered 2013-08-22 17:49:23 -04:00
parent 1c66f643ee
commit 3dcbbe7d83
2 changed files with 24 additions and 7 deletions

View file

@ -157,8 +157,8 @@
<Compile Include="Graphics\ScreenEffects\DimEffect.cs" />
<Compile Include="Graphics\ScreenEffects\FadeEffect.cs" />
<Compile Include="Graphics\ScreenEffects\FlashEffect.cs" />
<Compile Include="Services.cs" />
<Compile Include="IService.cs" />
<Compile Include="ServiceContainer.cs" />
</ItemGroup>
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\Portable\$(TargetFrameworkVersion)\Microsoft.Portable.CSharp.targets" />
<ItemGroup>

View file

@ -3,11 +3,11 @@ using System.Collections.Generic;
namespace Blarg.GameFramework
{
public static class Services
public class ServiceContainer : IDisposable
{
static Dictionary<Type, object> _services = new Dictionary<Type, object>();
Dictionary<Type, object> _services = new Dictionary<Type, object>();
public static void Register(object service)
public void Register(object service)
{
if (service == null)
throw new ArgumentNullException("service");
@ -22,9 +22,10 @@ namespace Blarg.GameFramework
((IService)service).OnRegister();
_services.Add(type, service);
Platform.Logger.Debug("ServiceContainer", "Registered object of type {0}.", type);
}
public static void Unregister(object service)
public void Unregister(object service)
{
if (service == null)
throw new ArgumentNullException("service");
@ -41,18 +42,20 @@ namespace Blarg.GameFramework
throw new InvalidOperationException("This is not the service object that was registered under this type.");
_services.Remove(type);
Platform.Logger.Debug("ServiceContainer", "Unregistered object of type {0}.", type);
if (registeredService is IService)
((IService)registeredService).OnUnregister();
}
public static T Get<T>() where T : class
public T Get<T>() where T : class
{
var type = typeof(T);
return Get(type) as T;
}
public static object Get(Type type)
public object Get(Type type)
{
if (type.IsValueType)
throw new ArgumentException("Services cannot be used with value types.", "type");
@ -61,6 +64,20 @@ namespace Blarg.GameFramework
_services.TryGetValue(type, out service);
return service;
}
public void Dispose()
{
Platform.Logger.Debug("ServiceContainer", "Disposing.");
foreach (var i in _services)
{
var service = i.Value;
if (service is IService)
((IService)service).OnUnregister();
}
_services.Clear();
}
}
}