【问题标题】:MvvmCross: IoC with Decorator pattern, two implementations of the same interfaceMvvmCross:带装饰器模式的 IoC,同一接口的两种实现
【发布时间】:2014-02-25 15:57:08
【问题描述】:

我想在我的一个 Mvx 项目中实现装饰器模式。也就是说,我希望有两个相同接口的实现:一个实现对所有调用代码都可用,另一个实现注入到第一个实现中。

public interface IExample
{
    void DoStuff();
}

public class DecoratorImplementation : IExample
{
    private IExample _innerExample;
    public Implementation1(IExample innerExample)
    {
        _innerExample = innerExample;
    }

    public void DoStuff()
    {
        // Do other stuff...
        _innerExample.DoStuff();
    }
}

public class RegularImplementation : IExample
{
    public void DoStuff()
    {
        // Do some stuff...
    }
}

是否可以连接 MvvmCross IoC 容器以使用包含 RegularImplementation 的 DecoratorImplementation 注册 IExample?

【问题讨论】:

    标签: inversion-of-control decorator ioc-container mvvmcross


    【解决方案1】:

    视情况而定。

    如果DecoratorImplementation 是单例,那么您可以执行以下操作:

    Mvx.RegisterSingleton<IExample>(new DecoratorImplementation(new RegularImplementation()));
    

    然后调用Mvx.Resolve&lt;IExample&gt;() 将返回DecoratorImplementation 的实例。

    但是,如果您需要一个新实例,不幸的是 MvvmCross IoC 容器不支持。如果您可以执行以下操作,那就太好了:

    Mvx.RegisterType<IExample>(() => new DecoratorImplementation(new RegularImplementation()));
    

    您将传入一个 lambda 表达式以创建一个新实例,类似于 StructureMap 的ConstructedBy

    无论如何,您可能需要创建一个工厂类来返回一个实例。

    public interface IExampleFactory 
    {
        IExample CreateExample();
    }
    
    public class ExampleFactory : IExampleFactory 
    {
        public IExample CreateExample() 
        {
            return new DecoratorImplementation(new RegularImplementation());
        }
    }
    
    Mvx.RegisterSingleton<IExampleFactory>(new ExampleFactory());
    
    public class SomeClass 
    {
        private IExample _example;
        public SomeClass(IExampleFactory factory) 
        {
             _example = factory.CreateExample();
        }
    }
    

    【讨论】:

    • 幸运的是,我只需要为单例执行此操作(目前),尽管为动态构造执行此操作也很好。这对于当前的项目应该很有效。谢谢!
    • unfortunately 上,它即将在 3.1.2 中推出 - 请参阅 github.com/MvvmCross/MvvmCross/pull/591
    猜你喜欢
    • 2013-05-04
    • 1970-01-01
    • 2012-02-29
    • 1970-01-01
    • 2012-02-16
    • 1970-01-01
    • 2020-11-02
    • 1970-01-01
    • 2016-04-29
    相关资源
    最近更新 更多