Creating new instances while still using Dependency Injection

ぃ、小莉子 提交于 2019-12-05 08:30:58

You're right. Using the IUnityContainer like this is no longer using Dependency Injection. Instead it's using the "Service Locator" pattern. What I usually do in cases like this is create an IFactory<T> interface, like this:

public IFactory<T>
{
    T Get();
}

Then implement the interface with a class that does know about and use the IUnityContainer. Set up your bindings so that IFactory<> requests will create an instance of this factory class. That way, you can inject the IFactory<Logger> interface into your ChatManager, and call .Get() any time you want a logger instance.

In general, I also think you should avoid passing the container around.

  • Add a IChatroomProvider to your design with a Create(string roomname) method
  • In ChatroomProvider, use the container to create named instances (the container will manage the lifecyle of each named instance for you so you don't need to manage a dictionary).
  • Register the ChatroomProvider with the container
  • Let ChatManager take a dependency on IChatroomProvider
  • When ChatManager needs a chatroom it can just ask its IChatroomProvider
  • Use the container to create the ChatManager instance
  • Logger instances will be created when chatrooms are created
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!