- 添加NuGet包引用 总共需要引入5个包 分别是 Unity.Container Unity.Interception.Configuration Unity.Interception Unity.Abstractions Unity
2.添加配置文件 配置文件节点如下:
`
/// <summary>
/// 通过静态构造函数初始化Unity容器
/// 执行且只执行一次
/// </summary>
static ContainerFactory()
{
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "CfgFiles\Unity.Config");//找配置文件的路径
Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
UnityConfigurationSection section = (UnityConfigurationSection)configuration.GetSection(UnityConfigurationSection.SectionName);
IUnityContainer container = new UnityContainer();
section.Configure(container, "webApiContainer");
_UnityContainer = container;
}
public static IUnityContainer BuildContainer()
{
return _UnityContainer;
}`
注意:配置文件下container的名称要与 工厂类的 的container名称相同
4.使用工厂类创建对象
var container = ContainerFactory.BuildContainer(); IUserService service = container.Resolve<IUserService>();
5.使用构造函数注入
A. 引入程序包 当前项目是WebApi Unity.AspNet.WebApi
B. API配置类中进行配置 WebApiConfig.cs
// Web API 配置和服务 config.DependencyResolver = new UnityDependencyResolver( ContainerFactory.BuildContainer());
C. 控制器中构造函数进行注入
private readonly IUserService service; public FirstController(IUserService service) { this.service = service; }