Lookup Method Injection?

Oct 22, 2010 at 11:30 AM

I was wondering if there is a simple way to support "lookup method injection" in Unity, specifically for objects with dependencies with a different ("shorter") lifetime than the main object?

I am working on a project which integrates Unity, WCF and Entity Framework, and I want to inject an ObjectContext into a service implementation class. I am using a custom lifetime manager to tie the ObjectContext to the WCF OperationContext. If I configure the service class to also use this custom manager, everything works as I expect. I get access to the same ObjectContext inside my service methods, which is disposed when the OperationContext ends. However, the service class is aggregating data from multiple sources, only one of which is a database, and I want to make it a singleton. The question is: "How can I get an injected ObjectContext which is NOT a singleton, but is still tied to the OperationContect"?

One approach would be to use the service locator pattern, and have my service methods directly retrieve the ObjectContext with a call to Resolve<T>(), but I don't want the service class to know anything about the container.

In Spring.NET, I used something called "lookup method injection", which used a combination of call signature convention and configuration for this case. Basically, the service class defines an abstract or virtual method like: "abstract MyContext GetContext();", and then the service class is configured with a "lookup-method" tag which takes the name of the method, and a reference to the container object which it should return.

Unity has a "method" tag, but to provide it with a reference to a container object, you need to use a "param" tag with a nested "value" tag, which means the method needs to take a parameter, which means when I call it in my service class, I need to provide it with a value...seems like a circular loop. I am guessing I can write my own intercpetor which will actually override my service method implementation (which is what happens in the Spring.NET case), but I was wondering if there is a more natural "unity way" of accomplishing this?

So, is there a recommended way of allowing objects to use dependencies with different ("shorter") lifetimes defined in the container?


Oct 23, 2010 at 1:17 AM

Take a dependency on a Func<T> - in your case a Func<ObjectContext>. This'll give you a delegate, that when called, will call back into the container. So you get the effect of calling container.Resolve<T> from inside your class, but you don't couple the object to the container.


Oct 23, 2010 at 4:39 AM

Thanks Chris. I knew there had to be a simpler answer to this than what I was playing around with. I even remember (now) reading your blog post on Auto Factories back in January, and wondering "when would I ever really want to do that?" Simple, elegant, and it works.