mirror of
https://github.com/greenshot/greenshot
synced 2025-07-16 10:03:44 -07:00
Introduced a very simple "singleton" service-locator, which allowed for a removal of specific implementations which were very limited. With this it's easier to access dependencies.
This commit is contained in:
parent
3ebdf3d2fe
commit
80d8f51fc5
53 changed files with 744 additions and 1230 deletions
55
GreenshotPlugin/Core/SimpleServiceProvider.cs
Normal file
55
GreenshotPlugin/Core/SimpleServiceProvider.cs
Normal file
|
@ -0,0 +1,55 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using GreenshotPlugin.Interfaces;
|
||||
|
||||
namespace GreenshotPlugin.Core
|
||||
{
|
||||
/// <summary>
|
||||
/// A really cheap and simple DI system
|
||||
/// </summary>
|
||||
public class SimpleServiceProvider : IServiceLocator
|
||||
{
|
||||
private readonly Dictionary<Type, List<object>> _services = new Dictionary<Type, List<object>>();
|
||||
|
||||
public static IServiceLocator Current { get; } = new SimpleServiceProvider();
|
||||
|
||||
public IEnumerable<TService> GetAllInstances<TService>()
|
||||
{
|
||||
var typeOfService = typeof(TService);
|
||||
if (!_services.TryGetValue(typeOfService, out var results))
|
||||
{
|
||||
yield break;
|
||||
}
|
||||
foreach (TService result in results)
|
||||
{
|
||||
yield return result;
|
||||
}
|
||||
}
|
||||
|
||||
public TService GetInstance<TService>()
|
||||
{
|
||||
return GetAllInstances<TService>().SingleOrDefault();
|
||||
}
|
||||
|
||||
public void AddService<TService>(IEnumerable<TService> services)
|
||||
{
|
||||
var serviceType = typeof(TService);
|
||||
if (!_services.TryGetValue(serviceType, out var currentServices))
|
||||
{
|
||||
currentServices = new List<object>();
|
||||
_services.Add(serviceType, currentServices);
|
||||
}
|
||||
|
||||
foreach (var service in services)
|
||||
{
|
||||
currentServices.Add(service);
|
||||
}
|
||||
}
|
||||
|
||||
public void AddService<TService>(params TService[] services)
|
||||
{
|
||||
AddService(services.AsEnumerable());
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue