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、使用配置文件注册对象
<configuration>
<configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,Microsoft.Practices.Unity.Configuration" />
</configSections>
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<typeAliases>
<!-- Lifetime manager types -->
<typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager,Microsoft.Practices.Unity" />
<typeAlias alias="external" type="Microsoft.Practices.Unity.ExternallyControlledLifetimeManager,Microsoft.Practices.Unity" />
<typeAlias alias="perThread" type="Microsoft.Practices.Unity.PerThreadLifetimeManager,Microsoft.Practices.Unity" />
<!-- User-defined type aliases -->
<typeAlias alias="Order" type="Demo.Order,Demo" />
</typeAliases>
<container>
<types>
<type type="Order" >
<lifetime type="singleton" />
</type>
</types>
</container>
</unity>
IUnityContainer container = new UnityContainer();
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功能使用: