asp.net团结依赖注入不能很好地工作 [英] asp.net unity dependency injection doesn't work well
问题描述
我使用asp.net的MVC框架3,我创建了实现IControllerFactory接口的UnityControllerFactory:
I am using the mvc 3 framework of asp.net, I have created a UnityControllerFactory that implements the IControllerFactory interface:
...
public class UnityControllerFactory : IControllerFactory
{
private IUnityContainer _container;
private IControllerFactory _innerFactory;
public UnityControllerFactory(IUnityContainer container)
: this(container, new DefaultControllerFactory())
{
}
protected UnityControllerFactory(IUnityContainer container,
IControllerFactory innerFactory)
{
_container = container;
_innerFactory = innerFactory;
}
public IController CreateController(RequestContext requestContext,
string controllerName)
{
try
{
IController controller = _container.Resolve<IController>(controllerName.ToLowerInvariant);
return controller;
}
catch (Exception ex)
{
var msg = ex.Message;
return _innerFactory.CreateController(requestContext, controllerName);
}
}
...
和在Application_Start(),我有:
and in the Application_Start(), I have:
protected void Application_Start() {
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
IUnityContainer container = GetUnityContainer();
container.RegisterType<IRepository<User>, LiveRepository<User>>();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
ControllerBuilder.Current.SetControllerFactory(new UnityControllerFactory(container));
...
}
我测试这与家庭控制器
I test this with a home controller
public class HomeController : Controller{
IRepository<User> userRepo;
public HomeController(IRepository<User> userRepo)
{
this.userRepo = userRepo;
}
...
}
当我运行应用程序时,我就无法构建家用控制器都没有。
在该行:
When I run the app, I can not build the home controller at all. in the line:
IController controller = _container.Resolve<IController>(controllerName.ToLowerInvariant);
我得到一个异常说:
I get an exception says:
**的依赖解析失败,TYPE =System.Web.Mvc.IController,名字=
HomeController的。在解析
**"Resolution of the dependency failed, type = "System.Web.Mvc.IController", name = "homecontroller". Exception occurred while: while resolving.
目前的异常时,该容器是:解决System.Web.Mvc.IController,HomeController的**
At the time of the exception, the container was: Resolving System.Web.Mvc.IController,homecontroller"**
但即使使用该行默认的控制器工厂:
but even with the default controller factory using the line:
_innerFactory.CreateController(requestContext, controllerName);
我还不能建立控制器所有,请帮助
I still cannot build the controller at all, please help
推荐答案
我建议你采取看的以下博客帖子这说明了如何使用统一定制DependencyResolver在ASP.NET MVC 3应用程序。
I would recommend you taking a look at the following blog post which illustrates how to use a custom DependencyResolver with Unity in an ASP.NET MVC 3 application.
这篇关于asp.net团结依赖注入不能很好地工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!