WinForms是否可以在不使用依赖注入框架的情况下注入依赖项?

huangapple go评论64阅读模式
英文:

Can WinForms have dependencies injected without using a dependency injection framework?

问题

I've read through many question on dependency injection in WinForms, with this being the most popular one. 我已经阅读了许多关于WinForms中的依赖注入的问题,其中这个是最受欢迎的一个。

I was shocked to discover that every example I've seen on this website uses a library for this job, such as Microsoft.Extensions.DependencyInjection. 这让我感到震惊的是,我发现这个网站上的每个示例都使用了一个库来完成这个工作,比如Microsoft.Extensions.DependencyInjection

This gives me my question: Can WinForms have dependencies injected without using a dependency injection framework? 这引发了我的疑问:WinForms是否可以在不使用依赖注入框架的情况下进行依赖注入?

For example, suppose that I have Form1 and Form2. 例如,假设我有Form1Form2

Opening the application opens Form1. 打开应用程序会打开Form1

Form1 has a single button, which opens Form2. Form1有一个按钮,点击它会打开Form2

Both forms must have a SqlConnection injected. 两个窗体都必须注入一个SqlConnection

Can this be done without a dependency injection framework? 这是否可以在不使用依赖注入框架的情况下完成?

For example, what forbids us from using plain-old constructor injection? 例如,是什么阻止我们使用普通的构造函数注入?

I would expect Application.Run(new Form1(MySqlConnectionHere)) to work in Main(). 我期望在Main()中使用Application.Run(new Form1(MySqlConnectionHere))来工作。

英文:

I've read through many question on dependency injection in WinForms, with this being the most popular one. I was shocked to discover that every example I've seen on this website uses a library for this job, such as Microsoft.Extensions.DependencyInjection. This gives me my question: Can WinForms have dependencies injected without using a dependency injection framework?

For example, suppose that I have Form1 and Form2. Opening the application opens Form1. Form1 has a single button, which opens Form2. Both forms must have a SqlConnection injected. Can this be done without a dependency injection framework? For example, what forbids us from using plain-old constructor injection? I would expect Application.Run(new Form1(MySqlConnectionHere)) to work in Main()

答案1

得分: 0

是的。

参见Mark Seemann的纯DI概念。

英文:

Yes.

See Mark Seemann's Pure DI concept.

huangapple
  • 本文由 发表于 2023年5月18日 02:31:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76275208.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定