0

我正在阅读以下教程。我在那个部分

IUnityContainer BuildUnityContainer()
{
    var container = new UnityContainer();

    container.RegisterType<IStoreService, StoreService>();
    container.RegisterType<IController, StoreController>("Store");        

    return container;
}

我的问题是如何做多个控制器?例如,如果我有 Store、Music 和 Owner 控制器,每个控制器都有自己的 I[Name]Service

4

4 回答 4

2

The new Unity 3 provides an integration point for MVC 4 out of the box. All the details on how to use it are here: http://msdn.microsoft.com/en-us/library/dn178463(v=pandp.30).aspx#sec17

You can also combine this with the registration by convention feature to register all your mappings like IFoo -> Foo: http://msdn.microsoft.com/en-us/library/dn178463(v=pandp.30).aspx#sec23

Regarding controllers, you do not need to register them explicitly in Unity, because if you ask Unity to resolve an instance of a concrete type that was not previously registered, it will build one up (injecting the dependencies using the longest constructor). MVC will ask Unity using the concrete types of the controllers, so they will work automatically.

于 2013-06-05T20:50:37.473 回答
1

您必须以相同的方式注册其中的每一个。或者您可能必须编写一个逻辑,您可以在其中使用反射获取所有可能的类型并在循环中注册它们。

于 2013-06-05T08:24:51.313 回答
0

看看http://autoregistration.codeplex.com/。它会自动注册类型以实现统一。大多数其他 IOC 容器也这样做。

于 2013-06-05T08:32:45.290 回答
0

看看http://weblogs.asp.net/shijuvarghese/archive/2008/10/24/asp-net-mvc-tip-dependency-injection-with-unity-application-block.aspx

第 3 步包含将依赖项注入控制器的代码还包括第 4 步中的以下代码:

ControllerBuilder.Current.SetControllerFactory(new myFinance.Web.Controllers.UnityControllerFactory(container));
于 2013-06-07T16:15:39.677 回答