依赖注入:如何传递注入容器?
(这个问题不依赖于特定的 IoC 框架,因此我的示例中的接口和类型都是元类型。只需将它们替换为您脑海中最喜欢的 IoC 框架的适当类型即可。)
在我的主要方法中,我通常设置我的容器做这样的事情:
static void Main()
{
IInjector in = new Injector();
in.Register<ISomeType>().For<SomeType>();
in.Register<IOtherType().For<OtherType>();
...
// Run actual application
App app = in.Resolve<App>();
app.Run();
}
我的问题是,如何发送注射器?我通常只是向其自身注册注入器,并将其注入到本身要进行注入的类型中,但我不确定这是否是正确的“模式”。
(This question does not rely on a specific IoC framework, so the interfaces and types in my samples are meta-types. Just replace them with the appropriate types for your favorite IoC framework in your head.)
In my main methods, I typically set up my container doing something like this:
static void Main()
{
IInjector in = new Injector();
in.Register<ISomeType>().For<SomeType>();
in.Register<IOtherType().For<OtherType>();
...
// Run actual application
App app = in.Resolve<App>();
app.Run();
}
My question is, how do you get the Injector sent around? I've normally just registered the injector with itself and had it injected into types that themselves are going to do injection, but I'm not sure if this is the proper "pattern".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不应该传递容器。
相反,您的入口点/主方法会向容器询问启动所需的对象 - 例如您的 App 对象/bean。然后,容器返回连接到
App
的完整对象图,这允许您在满足所有依赖项的情况下运行app.Run()
。对于对象了解容器,或者每个对象向容器询问其依赖项,这有点反模式 - 如果你这样做,那么你就没有反向控制,并且什么你所拥有的不是依赖注入——你仍然有对象询问他们需要什么,而不是被给予他们需要什么。
You shouldn't pass the container around.
Instead, your entry-point/main method asks the container for the objects it needs to get started - such as your App object/bean. The container then returns the full object graph connected to
App
, which allows you to runapp.Run()
, with all the dependencies satisfied.It's a bit of an anti-pattern for the objects to be aware of the container, or for each object to be asking the container for it's dependencies - if you do this then you have not inverted control and what you have is not dependency injection - you still have objects asking for what they need, rather than being given what they need.
最好避免注射注射器。只需创建您需要的类型,然后开始执行。我已经就此主题写了一篇较长的文章:访问 DI 容器
It's best to avoid injecting the injector. Just create the types you need, and then start executing. I've written a somewhat longer post on this topic: Accessing the DI container