开发者

Prism v4: Does it already include a way to handle value converters (as singletons)?

I found this little snippet of code on the web:

public abstract class ConverterExtension<T>: MarkupExtension, IValueConverter
    where T: class, new()
{
    private static T _converter = null;

    public override Object ProvideValue(IServiceProvider serviceProvider)
    {
        return _converter ?? (_converter = new T());
    }

    public abs开发者_开发知识库tract Object Convert(Object value, Type targetType, Object parameter, CultureInfo culture);

    public abstract Object ConvertBack(Object value, Type targetType, Object parameter, CultureInfo culture);
}

It basically does 2 things:

1. creates a singleton (very handy)

2. Allows you to use the converter without creating a static control (MarkupExtension)

What I'm wondering is if I use Prism v4 as my framework, is something like this already built in. I'd rather use whatever tools Prism has built in it than to write similar or duplicate code. I'm not that familiar with Prism, but I couldn't find anything like this in there. Oh, and I have a similar function for IMultiValueConverter.


IMHO the need for a singleton with regards to your converters to avoid the multiple instances is a bit of overkill as they are a resource of the View which they reside and will be GC'ed with the View and are in and of themselves very lightweight.

To your question though...Prism is geared towards building modular applications and is not in the realm of providing utility type classes/methods if that is what you were assuming. In terms of registering a singleton within Prism; this is certainly possible.

IUnityContainer container;
container.RegisterType<ISingleton, Singleton>(new ContainerControlledLifetimeManager());

The above code will associate any resolution for ISingleton with Singleton and by use of the ContainerControlledLifetimeManager() parameter will provide a single instance throughout the containers lifetime.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜