Dependency injection in thread that create objects

2019-06-02 10:31发布

If I have a thread that is started from the main application. In this thread events are generated. Everytime an event is generated an object is created. In that object a dependancy is needed so I want to inject that object. How can I pass this dependancy to the created object? Do I need to pass the depandancy downwards (and let the class that works in the thread know of the dependancy) or is there a nicer way to do this? I'm using Unity btw.

1条回答
Animai°情兽
2楼-- · 2019-06-02 11:12

The safest way is to let each thread build a new object graph at the beginning. Don't pass on dependencies by other threads.

With dependency injection, you try to centralize the knowledge about the lifetime of objects. This centralized place is called the Composition Root. When you start passing dependencies from one thread to the other, those parts of the code have to know whether it is safe to pass those dependencies. For instance, are those dependencies thread-safe? This might be trivial to analyze in many situations, but prevents you to change those dependencies with other implementations, since now you have to remember that there is a place in your code where this is happening and you need to know which dependencies are passed on. You are decentralizing this knowledge again, making it harder to reason about the correctness of your DI configuration and making it easier to misconfigure the container in a way that causes race conditions.

You can find more information about this subject on this wiki page: How to work with dependency injection in multi-threaded applications

查看更多
登录 后发表回答