当前类型是一个接口,无法构造。 你错过了类型映射吗?

我有一个控制器类,它负责双击命令,然后调用一个弹出窗口给用户的方法。 就像是 :

var popup = container.GetService(); 

在上面的行中,它抛出一个错误:当前类型PopupCommand.IPopupDataHandler是一个接口,无法构造。 你错过了类型映射吗?

我更新了包含container.GetService()方法的DLL,之前它曾经工作正常。

我尝试在谷歌搜索,但类似的问题与Unity更相关,我怀疑我的问题是否与Unity有关。

基本上,编译器会告诉您正在尝试实例化接口。

container.GetService()可能会带回一个名为PopupCommand.IPopupDataHandler的接口,您可能需要将其转换为您需要的类型或将类型更改为对象,您还应该检查方法的约束 – 它可以缺少new约束。

尝试使用Addin DefaultController Factory注册您的控制器。 三个步骤:步骤1 1.在项目中添加Class DefaultControllerFactory

 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; } } } 

第2步:在BuildUnityContainer方法的Bootstrap类中注册它

 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(); //RegisterTypes(container); container = new UnityContainer(); container.RegisterType(); UnityInterceptionExample.Models.ControllerFactory.MvcUnityContainer.Container = container; return container; } 

第3步:在Global.asax文件中注册它

 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)); } 

并且完成了。 可能这对你有用…快乐编码。