1

我的 MVC 3 控制器类中有一个方法,它接受两个参数:

public ActionResult MyMethod(string providerName, IAuthProvider providerImpl)

IAuthProvider在 Unity 容器中通过其名称注册了多个实现,如下所示:

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

因此,当调用该方法时,我希望根据第一个参数解析第二个参数。例如,如果第一个参数是“facebook”,则第二个参数必须从容器解析为以IAuthProvider名称“facebook”注册的实现。

我期待任何想法!

备注:我用的是Unity.2.1.505.0

4

2 回答 2

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
于 2012-05-12T07:57:47.193 回答
0

我认为,如果您使用 Autofac,您可以按照您的意图通过操作调用注入。但我不认为你可以用 Unity 做到这一点。我已经用 Autofac 完成了。

于 2013-05-31T20:18:28.090 回答