Вопрос

I have built a little static object for saving generic types to Isolated Storage on WP7. This works grand for older projects but some of the new projects use DI to manage configuration. I am a fan of DI as it means I can change the configuration in one place and have it filter down to all dependencies.

My thought was to create a namespace called Injection and wrap this object in an instance with an interface so I could inject it about. It would also enable me to swap out the storage handler for ones that require a more specific implementation.

Is this common practice or is this an anti pattern?

As a note, I want to keep the static option as not everyone needs or can use DI. I am simply trying to enable both with the least amount of duplication.

Это было полезно?

Решение

You see this all the time. Mostly it's to work around legacy code which is already static or sealed or doesn't implement any interfaces. While a base class instead of an interface, HttpContextBase is the most prominent example I can think of.

Since you want to keep the static option, that's basically the situation you are currently in, so go ahead and do it. I wouldn't create an Injection namespace, though, as that name says more about the mechanics than the role the object plays.

You don't write exactly how the class is static, but I'm assuming that we are talking about a static class with static methods.

A slightly more elegant solution (if you can change the class a bit) is to turn the static class into a Singleton. Then it could be static and implement the interface at the same time:

public class Foo : IFoo
{
    private readonly static Foo instance = new Foo();

    private Foo() { }

    public static Foo Instance
    {
        get { return Foo.instance; }
    }

    // IFoo member:
    public void InterfaceFoo()
    {
        Foo.LegacyFoo();
    }

    public static void LegacyFoo()
    {
        // Implementation goes here...
    }
}

I think the only refactoring required to arrive at such a solution is to make the class itself concrete and make it implement the interface as a Singleton.

Old clients could still access its methods by invoking Foo.LegacyFoo();

Другие советы

In my opinion, I'd let dependency injection container decide if it's transient or singleton - I don't know what framework you're using already, but most of them should control dependencies' life-cycle -.

And pre-dependency injection applications may maintain a static instance of this object as part of some application-wide state management.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top