1

I have got a method in my MVC 3 controller class, that accepts two parameters:

public ActionResult MyMethod(string providerName, IAuthProvider providerImpl)

I have got multiple implementations of IAuthProvider registered by its names in the Unity container as follows:

container.RegisterType<IAuthProvider, FacebookAuthProvider>("facebook");
container.RegisterType<IAuthProvider, GoogleAuthProvider>("google");

So, when the method is called I'd like the second argument to be resolved based on the first argument. For example, if the first argument was 'facebook' the second one must be resolved from the container to an IAuthProvider implementation registered by the name 'facebook'.

I look forward to any ideas!

Remark: I use Unity.2.1.505.0

Dmitrii
  • 1,247
  • 4
  • 14
  • 28

2 Answers2

3

There's so many things wrong with your example.

  1. Action Methods are not to be dependency injected with parameters, they are meant to be injected with values from the ModelBinder, that converts the name-value pairs that the browser is sending to objects that your action can accept.
  2. No DI framework can do the "bind the second parameter, based on first" out of the box because it is beyond their scope. If the DI can figure out what to inject for your IAuthProvider based on runtime values, it can only be because you have written some custom code for it.
  3. What you need is not in Unity, you need to write a custom ModelBinder for your requirements - Look here and here for examples. Extend the default ModelBinder, put a condition that if the action is MyMethod then look into the request values and self create the AuthProvider object and return the object.
  4. You can get the provider from the DI container, when you are writing your custom model binder. Also rethink the parameters, If your action is getting the correct provider, then why does it need the providerName? If it really needs it can it not get the name from the IAuthProvider itself? By checking the type or by using a .Name method? the providerName will only be used in the custom modelbinder
Community
  • 1
  • 1
Zasz
  • 12,330
  • 9
  • 43
  • 63
0

I think if you User Autofac you can inject by action invoke as you intended it. But I don't think you can do it it with Unity. I have done it with Autofac.