4

SimpleIoc想注册多个实现IProvider,例如:

SimpleIoc.Default.Register<IProvider, Provider1>();
SimpleIoc.Default.Register<IProvider, Provider2>();

所以我可以这样做:

var providers = SimpleIoc.GetAllInstances<IProvider>();

有没有办法做这样的事情?如果我按原样尝试,我会发现已经有一个类注册了IProvider.

4

1 回答 1

4

您可以通过实现基类并使用键控注册来做到这一点:

public interface IProvider { }
public abstract class BaseProvider : IProvider { }
public class Provider1 : BaseProvider { }
public class Provider2 : BaseProvider { }

[Test]
public void RegisterTwoImplementations_GetAllInstances_ReturnsBothInstances()
{
    SimpleIoc.Default.Register<Provider1>();
    SimpleIoc.Default.Register<Provider2>();

    SimpleIoc.Default.Register<BaseProvider>(() => 
            SimpleIoc.Default.GetInstance<Provider1>(), "a" );

    SimpleIoc.Default.Register<BaseProvider>(() =>
            SimpleIoc.Default.GetInstance<Provider2>(), "b");

    var result = SimpleIoc.Default.GetAllInstances<BaseProvider>();

    Assert.That(result, Is.Not.Null);
    Assert.That(result.Count(), Is.EqualTo(2));
    Assert.That(result.Any(x => x.GetType() == typeof(Provider1)), Is.True);
    Assert.That(result.Any(x => x.GetType() == typeof(Provider2)), Is.True);
}
于 2013-10-11T09:28:01.953 回答