【发布时间】:2020-10-02 09:49:48
【问题描述】:
我在 .NET 项目中使用 Ninject 来处理依赖注入。
我已将我的解决方案分为多个项目:
- 业务逻辑
- 前端
- 视图模型
他们精心挑选了参考资料:
- FrontEnd 引用了 ViewModels
- ViewModels 引用了 BusinessLogic
在应用程序的入口点(在我的例子中是前端)初始化 IoC 容器似乎很常见。
但是 FrontEnd 没有对业务逻辑的引用,所以我会得到一个未解决的引用错误。
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 容器中声明一些静态方法,以便外部项目可以注册自己的模块,但这会使事情变得更糟,因为这意味着 BackEnd 引用了 FrontEnd:
namespace FrontEnd
{
class ServiceModule : NinjectModule
{
public static void RegisterModule(Module m)
{
...
}
}
}
namespace BackEnd
{
class BackEnd
{
public void Init()
{
ServiceModule.RegisterModule(new Module() ...)
}
}
}
如何将我的所有服务配置到我的 IoC 容器中,而不会在项目之间出现可疑引用(如后端 -> 前端)?
【问题讨论】:
标签: dependency-injection inversion-of-control