[英]ASP.net MVC dependency injection with unity(DI container); how to inject dependency alias(specific types) based on the different controller types
I want to inject the specific dependencies using Unity OR any other DI container, based on the controller types. 我想根据控制器类型使用Unity或任何其他DI容器注入特定的依赖项。
Below is an example: 下面是一个示例:
The 2 dependencies are of type interface IAppLogger
: 2个依赖项的类型为接口
IAppLogger
:
1. NetworkLogger : IAppLogger
2. FileLogger : IAppLogger
Now below 2 controllers consume the dependency with abstraction IAppLogger. 现在,下面的2个控制器使用抽象IAppLogger消耗依赖项。
1. NetworkController depends on IAppLogger
2. FileController depends on IAppLogger
In my MVC project I have installed Unity and Unity.mvc3 packages. 在我的MVC项目中,我已经安装了Unity和Unity.mvc3软件包。 After that I got a bootstrap.cs file where I can register the types.
之后,我得到了bootstrap.cs文件,可以在其中注册类型。 Now how should I set the DependencyResolver to resolve
现在我应该如何设置DependencyResolver来解决
IAppLogger to NetworkLogger for controller NetworkController
AND 和
IAppLogger to FileLogger for controller FileController.
Edit: 编辑:
If things are dynamic with App then chaning the dependency types inside each controller would be hard as against doing it in service locator or resolver and have less footprint. 如果应用程序是动态的,那么与在服务定位器或解析器中进行更改相比,更改每个控制器内部的依赖项类型将很困难,并且占用空间较小。 In standalone app I can do it using alias while registering types.
在独立应用程序中,我可以在注册类型时使用别名。
Container.RegisterType<IAppLogger, NetworkLogger>("Network");
Container.RegisterType<IAppLogger, FileLogger >("File");
IAppLogger flogger = Container.Resolve<IAppLogger>("File");
IAppLogger nlogger = Container.Resolve<IAppLogger>("Network");
If NetworkController
should always operate with a NetworkLogger
then it should depend on NetworkLogger
, not on IAppLogger
. 如果
NetworkController
应始终与NetworkLogger
一起运行,则应取决于NetworkLogger
,而不取决于IAppLogger
。 Or maybe on INetworkLogger
if you want. 或者,如果需要,也可以在
INetworkLogger
。
The same goes for FileController
. FileController
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.