依赖注入之unity(winform方式)
要讲unity就必须先了解DI和IOC及DIP,如下链接提供DI和IOC的基础:https://www.cnblogs.com/zlp520/p/12015973.html
一.什么是unity?
unity是实现依赖注入的IOC容器,通过unity可以降低代码的耦合度。
二.下载并添加引用:
Microsoft.Practices.Unity.dll
Microsoft.Practices.Unity.Configuration.dll
二.实现途径?
1.代码实现:(核心代码)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using Microsoft.Practices.Unity.Configuration;
using Microsoft.Practices.Unity;
using ZLP.IBLL;
using ZLP.BLL; namespace ZLP.Win
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void Form1_Load(object sender, EventArgs e)
{
var container = new UnityContainer();//创建容器对象
container.RegisterType<IUserBLL, UserBLL>();//通过代码注入
var instance = container.Resolve<IUserBLL>();//从容器中获取对象
this.dataGridView1.DataSource = instance.GetList();
}
}
}
2.配置文件实现:(推荐,这种方式才是真正的彻底不耦合)
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
<unity>
<typeAliases>
<typeAlias alias="IUserBLL" type="ZLP.IBLL.IUserBLL,ZLP.IBLL" />
<typeAlias alias="UserBLL" type="ZLP.BLL.UserBLL,ZLP.BLL" />
</typeAliases>
<containers>
<container name="defaultContainer">
<type type="IUserBLL" mapTo="UserBLL" name="a"></type >
</container>
</containers>
</unity>
</configuration>
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using Microsoft.Practices.Unity.Configuration;
using Microsoft.Practices.Unity;
using ZLP.IBLL;
using ZLP.BLL; namespace ZLP.Win
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void Form1_Load(object sender, EventArgs e)
{
var container = new UnityContainer();//创建容器对象
var section = (UnityConfigurationSection)ConfigurationManager.GetSection(UnityConfigurationSection.SectionName);
section.Configure(container, "defaultContainer");
var instance = container.Resolve<IUserBLL>("a");//配置name这里就需要a,没有配置就不需要,多个类实现一个接口,通过name区分
this.dataGridView1.DataSource = instance.GetList();
}
}
}