Unity, WCF and context information

Dec 7, 2009 at 3:59 PM

Apologies if this has been asked before:

I've been following this post: http://avingtonsolutions.com/blog/post/2008/08/02/Uisng-Unity-with-a-WCF-Service.aspx and its great for instantiating my services and injecting their dependencies.

However, one of my dependencies is contextual - i.e. I will be passed a "key" in my service method which will then be used to return the correct instantiation of the concrete object.  Since the "key" is only passed in the method, not in the constructor, how can I resolve this object?

e.g.

MyController(IAccount account){..}

Request.AccountKey = "1234"

When I resolve my MyController...how do I pass it the correct IAccount object at runtime...so that I have a different controller per method call AND the correct "account" passed into each MyController?

 

Thanks for any assistance;

Dave.

 

Dec 8, 2009 at 2:50 AM

I think the ResolvedParameter might be what you're looking for.

You can register the MyController class and specify an injection constructor like this:

container.RegisterType<MyController>(new InjectionConstructor(new ResolvedParameter<IAccount>(Request.AccountKey)));

This tells the container when resolving a MyController object, use the constructor that takes the parameter IAccount object.  The value for that parameter will be the value of resolving an IAccount object having the registration name Request.AccountKey. (I assumed that in your case the Request.AccountKey is the registration name of the IAccount type mapping you want to use).

 

Sarah Urmeneta
Global Technology and Solutions
Avanade, Inc.
entlib.support@avanade.com

Dec 8, 2009 at 7:50 AM

Hi Sarah,

I think this is more than that:  This is a case of requiring contextual data to be passed into a class constructor - in this case an object that contains data for a specific ID.

This object can't be injected when the service starts up, since its not known then, and it must be retreived first before the other dependencies can be resolved.  The object to be retrieved can come from cache, database or new(...), and the controller then works with that object.

Thanks,

Dave.

Dec 11, 2009 at 4:36 AM

The easiest way to handle this is for the controller to have a dependency not on the IAccount object, but on an IAccountFactory. The IAccountFactory would have a method that takes the AccountKey and creates the actual IAccount object.