I talked about Lazy<T> in .NET 4, which is a pretty cool way to handle multi-threaded access to shared resources that are expensive to create. It does the equivalent of double-check locking to make sure that a resource is only instantiated once.
Most of use know about Lazy<T>, but did you know about Lazy<T,TMetadata> in System.ComponentModel.Composition? I didn’t until last night and I think it is pretty darn cool when you want to interrogate some Metadata to decide if you really want to instantiate the resource.
Lazy<T,TMetadata>
Let’s take a hypothetical situation where we have a number of Publisher Services that publish news on our behalf, but they are expensive to instantiate and we really only want to do this if they are indeed online.
We create two interfaces that represent the publisher service and its metadata as such:
public interface IPublisher
{
void Publish(News news);
}
public interface IPublisherMetadata
{
bool Online { get; }
}
We can now use these interfaces in a collection of Lazy<IPublisher,IPublisherMetadata> in say a NewsController that is responsible for handling the publishing of news. Inside the actual Publish Action we interrogate the IPublisherMetaData and only instantiate and call those publishers that indeed are online as such:
public class NewsController
{
private readonly IEnumerable<Lazy<IPublisher, IPublisherMetadata>> _publishers;
public NewsController(IEnumerable<Lazy<IPublisher, IPublisherMetadata>> publishers)
{
_publishers = publishers;
}
public void Publish(News news)
{
var publishers = _publishers.Where(p => p.Metadata.Online).ToList();
publishers.ForEach(p => p.Value.Publish(news));
}
}
This is brilliant. The Lazy<T,TMetadata> Class will be very handy in those scenarios where you have a number of expensive services that could achieve some end result but you want to filter them based on some configuration setting or runtime value. Very cool.

Comments