2014-02-25 54 views
1

我想在我的一个Mvx项目中实现装饰模式。也就是说,我想要有两个相同接口的实现:一个实现可用于所有调用代码,另一个实现可注入第一个实现。MvvmCross:与Decorator模式的IoC,相同接口的两个实现

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?

回答

1

这取决于。

如果DecoratorImplementation是单身,那么你可以这样做:

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

然后调用Mvx.Resolve<IExample>()将返回DecoratorImplementation实例。

但是,如果您需要新实例,不幸的是MvvmCross IoC容器不支持该实例。这将是很好,如果你可以这样做:

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

如果你传递一个lambda表达式来创建一个新的实例,类似StructureMap的ConstructedBy

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

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(); 
    } 
} 
+0

幸运的是,我只需要为单身人士(现在)做这个,尽管这样做对于动态建设来说也不错。这应该适用于这个当前的项目。谢谢! – Bognar

+0

在'不幸的'这是在3.1.2 - 见https://github.com/MvvmCross/MvvmCross/pull/591 – Stuart

+0

很好,谢谢你的抬头。 – Kiliman