为什么语言不将依赖注入集成在核心?

use*_*291 8 c# java frameworks dependency-injection inversion-of-control

为什么语言不在其核心中集成依赖注入(在最低级别:编译可能),因为依赖性是复杂性理论中所有邪恶的根源?这样可以避免使用Frameworks.

我宁愿瞄准编译语言.

我的问题类似于最近在.NET中使用动态引入的duck typing.为什么DI的未来类似?

更新:嘿伙计这个话题似乎很有意思,任何选民重新开放:)

Ste*_*ven 2

我个人可以看到这样做的好处。例如,我一直在编写这样的代码:

public class MyService : IService
{
    // Boilerplate!
    private readonly IDependency1 dep1;
    private readonly IDependency2 dep2;
    private readonly IDependency3 dep3;

    public MyService(IDependency1 dep1, IDependency2 dep2,
        IDependency3 dep3)
    {
        // More boilerplate!
        this.dep1 = dep1;
        this.dep2 = dep2;
        this.dep3 = dep3;
    }

    // Finally something useful
    void IService.DoOperation()
    {
       using (var context = this.dep1.CreateContext())
       {
           this.dep2.Execute(context);

           context.Commit();
       }

       this.dep3.Log("Success");
    }
}
Run Code Online (Sandbox Code Playgroud)

如果能够写成这样岂不是很好:

public class MyService : IService
{
    public MyService(private IDependency1 dep1, 
        private IDependency2 dep2, private IDependency3 dep3)
    {
    }

    void IService.DoOperation()
    {
       using (var context = this.dep1.CreateContext())
       {
           this.dep2.Execute(context);

           context.Commit();
       }

       this.dep3.Log("Success");
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望我可以省略所有管道,声明我的依赖字段并在构造函数中分配它们。

更新

我们的祈祷可能已被听到。C# 团队可能会添加“类定义的简洁语法”,例如 C# 6.0 中“可以直接从构造函数声明”的属性。希望这样的功能能够带来光明。

所以你的核心问题“为什么语言不在核心集成依赖注入?”,他们确实这样做了。Scala 和 F# 确实已经让这一切变得更加容易,C# 希望也能效仿。

与此同时,我尝试通过编写一个T4 模板来克服这个障碍,该模板在部分类中为您生成构造函数,但在应用程序中使用了几周后,它确实没有按预期工作。