In Unity 2 there is the concept of Automatic Factories to allow classes or services to defer instantiation of their dependencies to the last possible moment. This is particularly useful when the dependency is expensive to create and is not always used by the service. Think of it as lazy loading of dependencies just like we have lazy loading in O/R Mappers.
I mentioned similar functionality in Autofac in the following tutorial: Auto-Generated Factories in Autofac for Lazy Instantiation - LazyDependencyModule. I recommend you read that tutorial as it talks more about the concepts, etc., whereas here I will only mention a few comments and show you an example. Autofac also goes a bit further than Unity 2 by supporting Lazy<T> and Lazy<T,TMetadata> when using Autofac with the .NET Framework 4.
Automatic Factories in Unity 2
The example below shows Unity resolving a NewsController with a dependency on Func<Publisher> in its constructor. The idea here is that we are pretending that Publisher is expensive to create and we only want to resolve it on demand at time of use when the News is being published.
We do not have to register Func<Publisher> in the UnityContainer. Unity will automatically create a delegate matching that signature for us at runtime. The delegate will essentially do a container.Resolve<Publisher> on our behalf, allowing us to lazy load the Publisher without having a dependency on the container itself.
Here is some Unity 2 sample code:
class Program
{
static void Main(string[] args)
{
var container = new UnityContainer();
var controller = container.Resolve<NewsController>();
controller.Publish(new News());
Console.ReadLine();
}
}
public class NewsController
{
private readonly Func<Publisher> _getPublisher;
public NewsController(Func<Publisher> getPublisher)
{
_getPublisher = getPublisher;
}
public void Publish(News news)
{
_getPublisher().Publish(news);
}
}
public class Publisher
{
public void Publish(News news)
{
Console.WriteLine("Published...");
}
}
public class News { }
That's all there is to it. With a few small changes the Publisher is now being resolved on demand just when you need it.
Conclusion
I'll be giving a number of presentations on Enterprise Library 5 and Unity 2 this year at various Florida Code Camps and Florida .NET Developer Groups. First up is the South Florida Code Camp and then later I have presentations scheduled for IASA Tampa, Sarasota .NET Developer Group, and more to come.
Hope this helps.

Comments