Is there a way to get all the types in the Container
that implement a certain interface, even though they are not registered with that interface?
for example:
I have this interface:
public interface IMySpecificStorage : IMarkerStorage
{
... some important methods
}
and I register this in the container as: container.AddSingleton<IMySpecificStorage, MySpecificStorageClass()>()
I do have many of these kinds of specific storages, and at some point I want to get to them all from the container, at runtime.
Notionally I want to do something like this: container.ResolveAllServices<IMarkerStorage>()
but I know this does not work
Is is possible? or do I have to create my one way of keeping track of them? any suggested patterns for doing that?
mythz
2
No there’s no public API for this, I’d probably use a helper container class to help manage them, something like:
public class MarkerStorages
{
private readonly Container container;
public Type[] StorageTypes { get; }
public MarkerStorages(Funq.Container container, params Type[] storageTypes)
{
this.container = container;
StorageTypes = storageTypes;
}
public void RegisterAll() =>
StorageTypes.Each(x => container.RegisterAutoWiredType(x));
public List<IMarkerStorage> GetAllStorages() =>
StorageTypes.Map(type => (IMarkerStorage) container.Resolve(type));
}
container.Register(c => new MarkerStorages(c,
typeof(MyStorage1), typeof(MyStorage2)));
container.Resolve<MarkerStorages>().RegisterAll();
//Resolve example:
//var allStorages = container.Resolve<MarkerStorages>().GetAllStorages();
So to access from your Service class you could have a MarkerStorages
property that you call GetAllStorages()
to retrieve all instances.