ASP.NET MVC3使用Unity2.0实现依赖注入
创建空的ASP.NET MVC3项目,添加对Unity2.0动态库的引用。
方法1:在MSDN上下载Untity2.0,安装后,默认安装在C:\Program Files\Microsoft Unity Application Block 2.0下。
Microsoft.Practices.ServiceLocation.dll
Microsoft.Practices.Unity.Configuration.dll
Microsoft.Practices.Unity.dll
Microsoft.Practices.Unity.Interception.Configuration.dll
Microsoft.Practices.Unity.Interception.dll
方法2:使用Package Manager Console
工具—Library Package Manage—Package Manager Console,执行下面的命令:
要在上面新创建的ASP.NET MVC3项目中使用Unity依赖注入容器,需要在项目中添加一个类,它实现IDependencyResolver的接口,调用具体的Unity依赖注入容器。
代码如下:
public class UnityDependencyResolver : IDependencyResolver
{
readonly IUnityContainer _container;
public UnityDependencyResolver(IUnityContainer container)
{
this._container = container;
}
public object GetService(Type serviceType)
{
try
{
return _container.Resolve(serviceType);
}
catch
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
try
{
return _container.ResolveAll(serviceType);
}
catch
{
return new List<object>();
}
}
}
{
readonly IUnityContainer _container;
public UnityDependencyResolver(IUnityContainer container)
{
this._container = container;
}
public object GetService(Type serviceType)
{
try
{
return _container.Resolve(serviceType);
}
catch
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
try
{
return _container.ResolveAll(serviceType);
}
catch
{
return new List<object>();
}
}
}
在Global.asax.cs中,创建Unity依赖注入容器,在Application_Start 方法中,使用前面创建的UnityDependencyResolver 类注册Unity容器作为ASP.NET MVC的Service Locator。
代码如下:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
var container = new UnityContainer();
container.RegisterType<IMessages, Messages>();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}
同时容器使用RegisterType 注册了类型,在本例中注册了类型IMessage以及具体实现Messages
增加HomeController.cs,代码如下:
代码如下:
public class HomeController : Controller
{
private readonly IMessages messages;
public HomeController(IMessages messages)
{
this.messages = messages;
}
public ActionResult Index()
{
ViewBag.Message = messages.Welcome();
return View();
}
}
增加接口IMessges和具体实现类Messages,代码如下:
代码如下:
public interface IMessages
{
string Welcome();
}
public class Messages:IMessages
{
public string Welcome()
{
return "欢迎在ASP.NET MVC3中使用Unity2.0";
}
}
运行应用程序,Unity依赖注入容器会解析在HomeControler定义的依赖,Index页面显示"欢迎在ASP.NET MVC3中使用Unity2.0"