Skip to content

Instantly share code, notes, and snippets.

@TinkerWorX
Created February 26, 2018 17:29
Show Gist options
  • Save TinkerWorX/0bcfb3980727f09a5ffeeedd045d0ef5 to your computer and use it in GitHub Desktop.
Save TinkerWorX/0bcfb3980727f09a5ffeeedd045d0ef5 to your computer and use it in GitHub Desktop.
[Export(typeof(IItemService))]
[Export(typeof(IService))]
public class ActualItemService : IItemService, IService { }
[Export(typeof(IItemProcessingService))]
[Export(typeof(IService))]
public class ItemProcessingService : IItemProcessingService, IService
{
[Import]
privte IItemService itemService;
}
[Export(typeof(IItemService))]
[Export(typeof(IService))]
public class MockItemService : IItemService, IService { }
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