Unity的使用
1、Ioc功能使用:
1、介绍对象的生命周期
顾名思义 在容器中存在的实例,是可以定义其生命周期的。
Unity提供了 几种自带的 生命周期 管理类(常用的已标红)
ContainerControlledLifetimeManager 所谓的“单例模式”
PerThreadLifetimeManager,每线程生命周期管理器,就是保证每个线程返回同一实例
TransientLifetimeManager,瞬态生命周期,默认情况
ExternallyControlledLifetimeManager 外部控制生命周期管理器
HierarchicalLifetimeManager 分层生命周期管理器(没用过)
PerResolveLifetimeManager,这个生命周期是为了解决循环引用而重复引用的生命周期
2、使用代码注册对象
//对于已经存在的实例: OrderManagement orderManagement=new OrderManagement(); IUnityContainer container = new UnityContainer(); container.RegisterInstance(orderManagement); //使用Ioc内部创建 IUnityContainer container = new UnityContainer(); container.RegisterType<OrderManagement>(); //单例模式演示: IUnityContainer container = new UnityContainer(); container.RegisterType<OrderManagement>(new ContainerControlledLifetimeManager());
3、使用配置文件注册对象
1 <configuration> 2 <configSections> 3 <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,Microsoft.Practices.Unity.Configuration" /> 4 </configSections> 5 <unity xmlns="http://schemas.microsoft.com/practices/2010/unity"> 6 <typeAliases> 7 <!-- Lifetime manager types --> 8 <typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager,Microsoft.Practices.Unity" /> 9 <typeAlias alias="external" type="Microsoft.Practices.Unity.ExternallyControlledLifetimeManager,Microsoft.Practices.Unity" /> 10 <typeAlias alias="perThread" type="Microsoft.Practices.Unity.PerThreadLifetimeManager,Microsoft.Practices.Unity" /> 11 <!-- User-defined type aliases --> 12 <typeAlias alias="Order" type="Demo.Order,Demo" /> 13 </typeAliases> 14 <container> 15 <types> 16 <type type="Order" > 17 <lifetime type="singleton" /> 18 </type> 19 </types> 20 </container> 21 </unity>
1 IUnityContainer container = new UnityContainer(); 2 container.LoadConfiguration();
4、获取对象
container.Resolve<OrderManagement>();
5、在MVC中使用
//新建类 public class UnityDependencyResolver : IDependencyResolver { private readonly IUnityContainer _unityContainer; public UnityDependencyResolver(IUnityContainer container) { this._unityContainer = container; } public object GetService(Type serviceType) { try { return _unityContainer.Resolve(serviceType); } catch { return null; } } public IEnumerable<object> GetServices(Type serviceType) { try { return _unityContainer.ResolveAll(serviceType); } catch { return new List<object>(); } } }
//往 Application_Start() 里写入 var container = new UnityContainer(); //从配置文件 读取 注入实例 container.LoadConfiguration(); DependencyResolver.SetResolver(new UnityDependencyResolver(container));
在Controller 里面使用
public class HomeController : Controller { [Dependency] internal OrderManagement Management { set; get; } public ActionResult Index() { Management.Save(); return View(); } }
2、Aop功能使用: