Is Func appropriate to use as a ctor arg when applying Dependency Injection?

前端 未结 7 525
没有蜡笔的小新
没有蜡笔的小新 2021-01-31 12:09

Example:

public class BusinessTransactionFactory  where T : IBusinessTransaction
{
    readonly Func _createTransactio         


        
7条回答
  •  不思量自难忘°
    2021-01-31 12:34

    I personally don't like to see Func arguments as dependencies in my classes, because I think it makes the code less readable, but I know many developers don't agree with me. Some containers, such as Autofac, even allows you to resolve Func delegates (by returning a () => container.Resolve()).

    There are however, two cases where I don't mind to inject Func delegates:

    1. When the class that takes the Func constructor argument is located in the Composition Root, because in that case it's part of the container's configuration and I don't consider that part of the design of the application.
    2. When that Func is injected in a single type in the application. When more services start depending on that same Func, it would be better for readability to create a special I[SomeType]Factory interface and inject that.

提交回复
热议问题