问题
First time with Unity,
I have set up a class like this and registered in global.asax:
public class UnityControllerFactory : DefaultControllerFactory
{
private IUnityContainer container;
public UnityControllerFactory()
{
container = new UnityContainer();
RegisterTypes();
}
protected override IController GetControllerInstance(
System.Web.Routing.RequestContext requestContext,
Type controllerType)
{
return controllerType == null ?
null :
(IController)container.Resolve(controllerType);
}
private void RegisterTypes()
{
container.RegisterType<IUserRepository, EFUserRepository>();
}
}
Problem is, when the AccountController (default MVC project comes with) is called, it throws an error:
An exception of type 'Microsoft.Practices.Unity.ResolutionFailedException' occurred in Microsoft.Practices.Unity.dll but was not handled in user code
I can see there is a method to check if a type has been registered, but when I have made that check, how do I force the framework to use the default controller thingy?
if (container.IsRegistered(controllerType))
Here is my routing, as you can see... I want the login page to be the first page people see..
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/",
defaults: new {
controller = "Account",
action = "Login",
returnUrl = UrlParameter.Optional }
);
}
}
回答1:
Implemented a slightly different attempt at the factory:
public class UnityControllerFactory : DefaultControllerFactory
{
private IUnityContainer container;
private IControllerFactory defaultControllerFactory;
public UnityControllerFactory()
{
container = new UnityContainer();
defaultControllerFactory = new DefaultControllerFactory();
RegisterTypes();
}
public override IController CreateController(RequestContext ctx, string controllerName)
{
try
{
return container.Resolve<IController>(controllerName);
}
catch
{
return defaultControllerFactory.CreateController(ctx, controllerName);
}
}
private void RegisterTypes()
{
container.RegisterType<IUserRepository, EFUserRepository>();
}
}
still kicking up errors though... hmm.
来源:https://stackoverflow.com/questions/19897617/use-default-controller-container-if-unity-registered-types-has-not-got-this-curr