Call multiple classes with the same interface

后端 未结 3 614
-上瘾入骨i
-上瘾入骨i 2021-01-06 04:34

I have an interface like

public interface IAddressProvider
{
    string GetAddress(double lat, double long);
}

In my consuming class I wan

3条回答
  •  -上瘾入骨i
    2021-01-06 05:07

    Could you not just use container.GetAllInstances?, like so:

    var address = new List();
    foreach (var provider in container.GetAllInstances())
    {
        address.add(provider.GetAddress(lat, long));
    }
    

    Edit:

    I see what you mean now. If you're using StructureMap 2.x then I would recommend looking at the Conditionally clause. However this has been removed in version 3 in favour of creating your own builder class that should be responsible for returning the correct instance.

    For example:

    public class AddressProviderBuilder : IInstanceBuilder
    {
        private readonly IContainer container;
    
        public AddressProviderBuilder(IContainer container)
        {
            this.container = container;
        }
    
        public IAddressProvider Build()
        {
            foreach (var provider in this.container.GetAllInstances())
            {
                if (provider.GetAddress(lat, long) != null)
                {
                    return provider;
                }
            }
    
            return null;
        }
    }
    

提交回复
热议问题