使用DependencyResolver的控制器实例与MVC 3时出错控制器、实例、DependencyResolver、MVC

2023-09-03 17:13:41 作者:不用表白,亲完就跑

我使用MVC 3,并使用​​以下code中的应用程序启动时...

I'm using MVC 3 and using the following code when the application starts...

UnityContainer container = new UnityContainer();

new UnityMappings(container);

DependencyResolver.SetResolver(new UnityServiceLocator(container));

现在的应用程序运行我得到的时候下面的错误(但只是有时)...

Now when the app runs I'm getting the following error (but only sometimes)...

激活出错   IControllerFactory,键

Activation error occured while trying to get instance of type IControllerFactory, key ""

有趣的是,如果我继续与web请求,该网站的正常工作。

Interestingly, if I continue with the web request, the website works normally.

任何想法?我什么也看不见,我从什么时候这个工作的罚款之前,做不同。

Any ideas? I can't see what I'm doing differently from before when this worked fine.

欢呼声中,伊恩。

推荐答案

MVC3要求远比从 DependencyResolver 只是控制器的更多。对于大多数人MVC3回落到默认的实施情况的DependencyResolver不返回一个实例。

MVC3 requests a lot more than just controllers from the DependencyResolver. For most of them MVC3 falls back to the default implementation in case the DependencyResolver does not return an instance.

在你的情况下,它要求 IControllerFactory 这是未知的,你的IoC容器,它抛出一个捕获的 UnityServiceLocator 执行和返回null。 MVC然后回落到默认的控制器工厂。

In your case it requests the IControllerFactory which is unknown to your IoC container and it throws an exception which is caught by the UnityServiceLocator implementation and null is returned. MVC then falls back to the default controller factory.

不像其他的IoC容器统一并没有提供一个可选的 TryResolve ,因此不支持正确的exceptionless实施 DependencyResolver 。

Unlike other IoC containers Unity does not provide an optional TryResolve and therefore does not support a proper exceptionless implementation of the DependencyResolver.