1

I'd like to implement the Decorator pattern in one of my Mvx projects. That is, I'd like to have two implementations of the same interface: one implementation that is available to all of the calling code, and another implementation that is injected into the first implementation.

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...
    }
}

Is it possible to wire up the MvvmCross IoC container to register IExample with a DecoratorImplementation containing a RegularImplementation?

chkimes
  • 1,127
  • 13
  • 20

1 Answers1

1

It depends.

If DecoratorImplementation is a Singleton, then you could do something like:

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

Then calls to Mvx.Resolve<IExample>() will return the instance of DecoratorImplementation.

However, if you need a new instance, unfortunately the MvvmCross IoC Container doesn't support that. It would be nice if you could do something like:

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

Where you'd pass in a lambda expression to create a new instance, similar to StructureMap's ConstructedBy.

Anyway, you may need to create a Factory class to return an instance.

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();
    }
}
Kiliman
  • 18,460
  • 3
  • 39
  • 38
  • Luckily I only need to do this for singletons (for now), though it would be nice to do this for dynamic construction as well. This should work great for this current project. Thanks! – chkimes Feb 25 '14 at 20:22
  • On the `unfortunately` it's coming in 3.1.2 - see https://github.com/MvvmCross/MvvmCross/pull/591 – Stuart Feb 25 '14 at 21:44