前言
其实我一直是不太建议在Winform中使用依赖注入的,基于Winform本身的开发特性——灵活又死板,内聚又耦合,所以我一直觉得在对象在需要时创建、灵活实例化是比较合适的,而且Winform开发大概率会碰到循环依赖的问题,目前市面上的IOC容器,我觉得对于这一块的处理并不是特别完美(虽然可以用)。当然,这可以归根到是项目的结构问题,如果你有很强的抽象能力、架构能力,确实可以忽略这个问题。
本文主要通过AutoFac
实现在Winform中使用依赖注入,分别注入Service以及Form,以此为基础可以实现一个小项目的蓝本。
开发环境:.NET Framework版本:4.8
开发工具:Visual Studio 2022
实现步骤
首先使用Nuget安装AutoFac。
分别创建一个
IUser
接口以及实现类User
public interface IUser
{
int Add(int a, int b);
}
public class User : IUser
{
public int Add(int a, int b)
{
return a + b;
}
}
分别创建两个窗体,并在其构造函数中进行注入调用,这里会使用
Lazy
来解决循环依赖的问题,因为这在Winform开发中是非常常见的一种情况(这里值得注意的是,使用了Lazy
的话,千万不能在构造函数中取其Value值)。
public partial class Form1 : Form
{
readonly IUser _user;
readonly Form2 _form2;
public Form1(IUser user, Form2 form2)
{
_user= user;
_form2= form2;
InitializeComponent();
}
public partial class Form2 : Form
{
readonly IUser _user;
readonly Lazy<Form1> _form1;
public Form2(IUser user, Lazy<Form1> form)
{
_user = user;
_form1=form;
InitializeComponent();
}
分别在窗体中实现对Service(User)的调用,以及窗体之间的相互弹出
//Form1
private void button1_Click(object sender, EventArgs e)
{
int result = _user.Add(4, 5);
MessageBox.Show(result + "");
}
private void button2_Click(object sender, EventArgs e)
{
_form2.ShowDialog();
}
//Form2
private void button1_Click(object sender, EventArgs e)
{
int result = _user.Add(2, 6);
MessageBox.Show(result + "");
}
private void button2_Click(object sender, EventArgs e)
{
_form1.Value.Show();
}
最后在
Program
文件中实现IOC容器以及注入
internal static class Program
{
public static IContainer Container { get; set; }
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Register();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(Container.Resolve<Form1>());
// Application.Run(new Form1());
}
static void Register()
{
var builder = new ContainerBuilder();
//服务注入
builder.RegisterType<User>().As<IUser>();
//窗体注入
var dataAccess = Assembly.GetExecutingAssembly();
builder.RegisterAssemblyTypes(dataAccess)
.Where(t => t.BaseType == typeof(Form));
Container = builder.Build();
}
}
实现效果
☛☛☛点击此处下载源码☚☚☚