Try Addin DefaultController Factory to register your controller. Three steps: Step 1 1. Add the DefaultControllerFactory class to your project
public class ControllerFactory :DefaultControllerFactory { protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { try { if (controllerType == null) throw new ArgumentNullException("controllerType"); if (!typeof(IController).IsAssignableFrom(controllerType)) throw new ArgumentException(string.Format( "Type requested is not a controller: {0}", controllerType.Name), "controllerType"); return MvcUnityContainer.Container.Resolve(controllerType) as IController; } catch { return null; } } public static class MvcUnityContainer { public static UnityContainer Container { get; set; } } }
Step 2: register it in the Bootstrap class in the BuildUnityContainer method
private static IUnityContainer BuildUnityContainer() { var container = new UnityContainer(); // register all your components with the container here // it is NOT necessary to register your controllers // eg container.RegisterType<ITestService, TestService>(); //RegisterTypes(container); container = new UnityContainer(); container.RegisterType<IProductRepository, ProductRepository>(); UnityInterceptionExample.Models.ControllerFactory.MvcUnityContainer.Container = container; return container; }
Step 3: register it in the Global.asax file
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterAuth(); Bootstrapper.Initialise(); ControllerBuilder.Current.SetControllerFactory(typeof(ControllerFactory)); }
And finished. Maybe this will work for you ... Happy coding.
user5888504
source share