chkimes
chkimes

Reputation: 1137

MvvmCross: IoC with Decorator pattern, two implementations of the same interface

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?

Upvotes: 1

Views: 666

Answers (1)

Kiliman
Kiliman

Reputation: 20312

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

Upvotes: 1

Related Questions