Dependency injection 聚合所有依赖项注入模块是否常见?
我在一个.NET项目中使用Ninject来处理依赖注入 我已将解决方案分为多个项目:Dependency injection 聚合所有依赖项注入模块是否常见?,dependency-injection,inversion-of-control,Dependency Injection,Inversion Of Control,我在一个.NET项目中使用Ninject来处理依赖注入 我已将解决方案分为多个项目: 业务逻辑 前端 视图模型 他们仔细挑选了参考资料: 前端具有对ViewModels的引用 ViewModels引用了BusinessLogic 在应用程序的入口点初始化IoC容器似乎很常见(在我的例子中,这是前端) 但是前端没有对业务逻辑的引用,所以我将得到一个未解决的引用错误 namespace FrontEnd { class ServiceModule : NinjectModule
- 业务逻辑
- 前端
- 视图模型
- 前端具有对ViewModels的引用
- ViewModels引用了BusinessLogic
namespace FrontEnd
{
class ServiceModule : NinjectModule
{
public override void Load()
{
this.Bind<AccountViewModel>().ToSelf();
this.Bind<DetailsViewModel>().ToSelf();
this.Bind<ISessionContext>().To<SessionContext>()
.InSingletonScope();
this.Bind<INavigationViewModel>().To<NavigationViewModel>();
this.Bind<ILoggingService>().To<LoggingService>();
// This will not work because MathClient is in the Business Logic assembly
this.Bind<IMathProvider>().To<MathClient>()
.WithConstructorArgument("binding", new BasicHttpBinding())
.WithConstructorArgument("remoteAddress", new EndpointAddress("http://localhost/server.php"));
}
}
}
如何将所有服务配置到IoC容器中,而不在项目之间存在可疑引用(如后端->前端)?将所有依赖项注入配置代码放在一个位置,即项目中,这是一种常见且良好的做法 假设您决定在项目之间拆分DI配置代码。事实上,这在技术上是可能的。您可以在
BusinessLogic
程序集中创建一个单独的ninject模块。但在那之后,您必须将此模块加载到FrontEnd
程序集中。这意味着您仍然必须将引用从FrontEnd
assembly添加到BusinessLogic
assembly
只需在顶级程序集中配置所有服务。如果您需要添加一些对低级模块的引用,请这样做。它比从BusinessLogic
程序集向后引用某个顶级程序集或从BusinessLogic
程序集引用DI库要好得多
看看这张马克·希曼的照片。你的作文代码应该是
尽可能靠近应用程序的入口点
以及:
DI容器只能从组合根引用。所有其他模块都不应引用容器
重复:
namespace FrontEnd
{
class ServiceModule : NinjectModule
{
public static void RegisterModule(Module m)
{
...
}
}
}
namespace BackEnd
{
class BackEnd
{
public void Init()
{
ServiceModule.RegisterModule(new Module() ...)
}
}
}