英文:
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
. 例如,假设我有Form1
和Form2
。
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概念。
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论