Error when using DependencyResolver for Controller

2019-05-09 12:39发布

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)...

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

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.

Cheers, Ian.

2条回答
成全新的幸福
2楼-- · 2019-05-09 13:25

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.

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.

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

查看更多
劫难
3楼-- · 2019-05-09 13:33

I would suggest first looking through the config and make sure everything is correct there, then I would make sure I had all the assemblies needed for Unity referenced in the project. That error message may (in my experience) point to an error in config or a missing DLL, perhaps an assembly you want to load in the container or another DLL needed by a DLL loaded by Unity?

Hope this helps.

查看更多
登录 后发表回答