本文介绍了MvvmLight SimpleIoc和多种具体实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 使用 SimpleIoc 我要注册 IProvider 的多个实现,是这样的: SimpleIoc.Default.Register< IProvider,Provider1>(); SimpleIoc.Default.Register< IProvider,Provider2之间>(); 因此,我可以做的: VAR提供商= SimpleIoc.GetAllInstances< IProvider>(); 有没有办法做这样的事情?如果我尝试它看作是我得到的已经有对 IProvider 注册一类。 解决方案 公共接口IProvider {} $:/ DIV> 您可以通过实现一个基类,使用键值注册办呢b $ b酒店的公共抽象类BaseProvider:IProvider {} 公共类Provider1:BaseProvider {} 公共类Provider2之间:BaseProvider {} [测试] 公共无效RegisterTwoImplementations_GetAllInstances_ReturnsBothInstances() { SimpleIoc.Default.Register< Provider1>(); SimpleIoc.Default.Register<&Provider2的GT;(); SimpleIoc.Default.Register&所述; BaseProvider>(()=> SimpleIoc.Default.GetInstance&所述; Provider1>(),是); SimpleIoc.Default.Register&所述; BaseProvider>(()=> SimpleIoc.Default.GetInstance&所述; Provider2的>(),B); VAR的结果= SimpleIoc.Default.GetAllInstances< BaseProvider>(); Assert.That(结果,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); } With SimpleIoc I'd like to register multiple implementations of IProvider, something like:SimpleIoc.Default.Register<IProvider, Provider1>();SimpleIoc.Default.Register<IProvider, Provider2>();So I can do:var providers = SimpleIoc.GetAllInstances<IProvider>();Is there a way to do something like this? If I try it as is I get that there is already a class registered for IProvider. 解决方案 You can do it by implementing a base class and using keyed registrations: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);} 这篇关于MvvmLight SimpleIoc和多种具体实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 09-25 20:17