我想将Unity用作ASP.NET MVC 3应用程序的IoC容器,但我的UnityDependecyResolver
课程出现问题。它目前看起来像这样(从网上的某个地方复制,因为我不认为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>();
}
}
}
但是,在尝试访问任何控制器时出现此运行时错误:
IControllerFactory'System.Web.Mvc.DefaultControllerFactory'未返回名为'Account'的控制器。
This StructureMap article建议我应该修改GetService
方法,但是,我对MVC和Unity都很陌生,我不确定它究竟应该是什么样子。
答案 0 :(得分:1)
查看codeplex上的Unity.MVC project。
答案 1 :(得分:0)
这是我的实施,对我来说它有效
public class UnityResolver : IDependencyResolver
{
private readonly IUnityContainer _container;
public UnityResolver(IUnityContainer container)
{
_container = container;
}
public object GetService(Type serviceType)
{
if (typeof(IController).IsAssignableFrom(serviceType))
{
return _container.CreateChildContainer().Resolve(serviceType);
}
if (_container.IsRegistered(serviceType))
{
return _container.CreateChildContainer().Resolve(serviceType);
}
return null;
}
public IEnumerable<object> GetServices(Type serviceType)
{
return _container.CreateChildContainer().ResolveAll(serviceType);
}
}