Unity 2.0:如何在 CTor 注入上创建子容器?
我有一个 MessageSender 类,其构造函数如下所示:
public MessageSender(IInputComponent input, IOutputComponent output)
{
m_Input = input;
m_Output = output;
}
这是我实例化它的方式:
Container.RegisterType<IMessageSender, MessageSender>();
Container.RegisterType<IInputComponent, KeyboardInput>();
Container.RegisterType<IOutputComponent, ScreenOutput>();
Container.RegisterType<ILogger, Logger>();
return Container.Resolve<IMessageSender>();
这是 KeyboardInput 构造函数:
public KeyboardInput(IUnityContainer container)
{
m_Container = container;
m_Logger = container.Resolve<ILogger>();
}
我希望 KeyboardInput 实例将子容器接收到其构造函数,因此它将从子容器解析其记录器,并且不是父母。
我怎样才能做到这一点?
谢谢!
I have a MessageSender class that its constructor looks like this:
public MessageSender(IInputComponent input, IOutputComponent output)
{
m_Input = input;
m_Output = output;
}
This is how I instantiate it:
Container.RegisterType<IMessageSender, MessageSender>();
Container.RegisterType<IInputComponent, KeyboardInput>();
Container.RegisterType<IOutputComponent, ScreenOutput>();
Container.RegisterType<ILogger, Logger>();
return Container.Resolve<IMessageSender>();
Here is the KeyboardInput consutructor:
public KeyboardInput(IUnityContainer container)
{
m_Container = container;
m_Logger = container.Resolve<ILogger>();
}
I want the KeyboardInput instance to receive a child container to its constructor, so it will resolve its logger from the child container and not the parent.
How can I accomplish that?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不应该依赖 KeyboardInput 或任何其他类中的 IUnityContainer。 DI 容器应该解析所有组件并避开 - 我称之为 DI 的好莱坞原则。保留对容器的引用会导致抽象服务定位器反模式,所以这是一个非常糟糕的主意。
Krzysztof Koźmic 最近的这些帖子很好地解释了这一点:
总是可以重新设计对象模型,以便不需要引用容器。为什么你认为你需要 KeyboardInput 中的容器?
You are not supposed to take a dependency on IUnityContainer in KeyboardInput or any other class. A DI Container should resolve all components and get out of the way - I call this the Hollywood Principle for DI. Keeping a reference to the container leads towards the Abstract Service Locator anti-pattern, so that's a spectacularly bad idea.
These recent posts by Krzysztof Koźmic explains it pretty well:
It's always possible to redesign the object model so that referencing the container isn't necessary. Why do you think you need the container in KeyboardInput?