MvvmLight SimpleIoc和多个具体实现

时间:2013-10-10 17:00:58

标签: c# mvvm-light ioc-container

使用SimpleIoc我想注册IProvider的多个实现,例如:

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

所以我能做到:

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

有没有办法做这样的事情?如果我按原样尝试,我已经注册了IProvider

1 个答案:

答案 0 :(得分: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);
}