On May 24th my children are out for the summer and my status of Part-Time Stay-at-Home Dad is happily elevated to more of a Full-Time Position. I so look forward to the summers where we can spend more time at the beach, kayaking on the bay, fishing, and hanging out at a number of places where we enjoy yearly passes.
Since it ain't summer yet, however, I wanted to continue my little progression on the Policy Injection Application Block that I talked about in the following 2 posts:
One of the things that had irked me is that we don't have a Dependency-Injection Tool from Microsoft and the Policy Injection Application Block doesn't provide any dependency injection facilities. I say "had", because I don't truly know that they could create a good dependency-injection tool or at least be as responsive in creating new versions and maintenance releases as the OSS Community.
We can use a third-party Dependency-Injection Tool, like StructureMap, and use it with the Policy Injection Application Block to get both dependency injection and Aspect-Oriented Programming capabilities.
Getting Object Instances
If you are using StructureMap for your Dependency Injection, you are probably calling ObjectFactory directly to get your object instances:
T instance = ObjectFactory.GetInstance<T>();
As cool as StructureMap is, I still like creating a wrapper for it just so that I can perhaps switch to another tool or strategy for getting my object instances. I tend to wrap it up in an IoC Class:
public static class IoC
{
public static T Resolve<T>()
{
return ObjectFactory.GetInstance<T>();
}
}
I could see where this may seem like a waste of time, except now that the Policy Injection Application Block has been released, I can now sneak it into my IoC Class and my client code is none the smarter:
public static class IoC
{
public static T Resolve<T>()
{
// Get From StructureMap
T instance = ObjectFactory.GetInstance<T>();
// Wrap Using Policy Injection Application Block
return PolicyInjection.Wrap<T>(instance);
}
}
Back To Caching
So now if we go back to the IService as talked about in the last couple of posts where I want to simply cache the data for 30 minutes in this case:
public interface IService
{
IList GetData();
}
public class Service : IService
{
[CachingCallHandler(0,30,0)]
public IList GetData()
{
return new ArrayList();
}
}
Registering and obtaining the service is pretty simple:
class Program
{
static void Main(string[] args)
{
// Register Service
StructureMapConfiguration.UseDefaultStructureMapConfigFile = false;
StructureMapConfiguration.BuildInstancesOf<IService>().
TheDefaultIsConcreteType<Service>().AsSingletons();
// Get Service
IService service = IoC.Resolve<IService>();
}
}
Here we get the best of both worlds - dependency injection via a 3rd party tool and the Policy Injection Application Block.
Cool Stuff!
Recent Enterprise Library Posts
Drinking: Gyokuro Green Tea