1、通过NuGet 加载程序包: Unity ;
2、建立一个反转类: NDependencyResolver.cs
public class NDependencyResolver : IDependencyResolver
{
#region IDependencyResolver 成员
/// <summary>
/// 依赖注入容器
/// </summary>
private IUnityContainer _unityContainer;
/// <summary>
/// 构造
/// </summary>
/// <param name="aUnityContainer">依赖注入容器</param>
public NDependencyResolver(UnityContainer aUnityContainer)
{
_unityContainer = aUnityContainer;
}
public object GetService(Type aServiceType)
{
try
{
return _unityContainer.Resolve(aServiceType);
}
catch
{
/// 按微软的要求,此方法,在没有解析到任何对象的情况下,必须返回 null,必须这么做!!!!
return null;
}
}
public IEnumerable<object> GetServices(Type aServiceType)
{
try
{
return _unityContainer.ResolveAll(aServiceType);
}
catch
{
/// 按微软的要求,此方法,在没有解析到任何对象的情况下,必须返回空集合,必须这么做!!!!
return new List<object>();
}
}
#endregion
}
public class MvcApplication : System.Web.HttpApplication
{
..............
protected void Application_Start()
{
.........
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
//加载依赖注入
<span style="color:#ff0000;"> RegisterDependency();</span>
}
<span style="color:#ff0000;">/// <summary>
/// IOC 容器初始化
/// </summary>
private static UnityContainer _Container;
public static UnityContainer Container
{
get
{
if (_Container == null)
{
_Container = new UnityContainer();
}
return _Container;
}
}
protected void RegisterDependency()
{
Container.RegisterType</span><span style="color:#009900;"><WarehouseI, WarehouseIntFace></span><span style="color:#ff0000;">();
DependencyResolver.SetResolver(</span><span style="color:#009900;">new NDependencyResolver</span><span style="color:#ff0000;">(Container));
}</span>
}
4、调运action中加入依赖注入:
[Dependency]
public WarehouseI warehouseIntFace { get; set; }