Skip to content

Instantly share code, notes, and snippets.

@TinkerWorX
Created February 14, 2018 15:23
Show Gist options
  • Save TinkerWorX/3b24784ad1a9d366685b2bf6ede65c03 to your computer and use it in GitHub Desktop.
Save TinkerWorX/3b24784ad1a9d366685b2bf6ede65c03 to your computer and use it in GitHub Desktop.
public class ServiceManager
{
[NotNull]
public static ServiceManager Instance { get; } = new ServiceManager();
#pragma warning disable 649
// ReSharper disable CollectionNeverUpdated.Local
[ImportMany(typeof(IService))]
private List<IService> importedServices;
// ReSharper restore CollectionNeverUpdated.Local
#pragma warning restore 649
private readonly Dictionary<Type, object> services;
private ServiceManager()
{
Log.Information($"Assembling services.");
var catalog = new AssemblyCatalog(typeof(ServiceManager).Assembly);
var container = new CompositionContainer(catalog);
container.SatisfyImportsOnce(this);
foreach (var importedService in this.importedServices)
Log.Information($"Found '{importedService.ServiceType.FullName}' service.");
Log.Information($"Found {this.importedServices.Count} service(s).");
this.services = this.importedServices.ToDictionary(e => e.ServiceType, e => (object)e);
}
public void Add([NotNull]Type type, [NotNull]object service) => this.services.Add(type ?? throw new ArgumentNullException(nameof(type)), service ?? throw new ArgumentNullException(nameof(service)));
public void Add<T>([NotNull]object service) => this.services.Add(typeof(T), service);
[NotNull]
public T Get<T>() => (T)this.services[typeof(T)];
[CanBeNull]
public T GetOrDefault<T>()
{
if (this.services.TryGetValue(typeof(T), out var service))
return (T)service;
return default(T);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment