8

我有一个新的MVC Web项目,我使用MVC和WebApi。我已经在我的全局文件中使用以下代码设置简单注入器(从nuGet 2.5.2版本)简单的注射器 - 没有为此对象定义的无参数构造函数

// Register Injectors 
SimpleInjectorConfig.Register(); 

以我SimpleInjectorConfig.cs文件I具有

public class SimpleInjectorConfig 
{ 
    public static void Register() { 
     // Create the container as usual. 
     Container container = new Container(); 

     // services 
     container.Register<IService, MyService>(); 

     // data 
     container.Register<IRepository, MyRepository>(); 

     // Register your types, for instance using the RegisterWebApiRequest 
     // extension from the integration package: 
     container.RegisterMvcControllers(
      System.Reflection.Assembly.GetExecutingAssembly()); 

     container.RegisterMvcAttributeFilterProvider(); 

     // This is an extension method from the integration package. 
     container.RegisterWebApiControllers(GlobalConfiguration.Configuration); 

     // verify its all ok 
     container.Verify(); 

     // add dependency 
     GlobalConfiguration.Configuration.DependencyResolver = 
      new SimpleInjectorWebApiDependencyResolver(container); 
    } 
} 

现在我有2个控制器中,1是的WebAPI控制器和1是一个正常的MVC控制器。

我的WebAPI控制器工作正常,看起来像这样

public class MyApiController : ApiController 
    { 
     private IService _service; 

     public MyApiController(IService service) 
     { 
      _service = service; 
     } 

     /// <summary> 
     /// GET api/<controller>/5 
     /// </summary> 
     /// <param name="id"></param> 
     /// <returns></returns> 
     public IHttpActionResult Get(int id) 
     { 
      // i get my entity here and return it 
      EntityObject myEntity = _service.Get(id); 
      return Ok(myEntity); 
     } 
    } 

正如我说上面的代码工作正常,我可以执行的URL,并返回我期望的那样。

现在我有我的MVC视图控制器,看起来非常类似于上述情况,这里是

public class MyController : Controller 
{ 
    private IService _service; 

    public MyController(IService service) 
    { 
     _service = service; 
    } 

    public ActionResult Index() 
    { 
     return Search(); 
    } 

    // Company/Search 
    public ActionResult Search() 
    { 
     return View(); 
    } 
} 

现在我无法理解在所有的,为什么我不断收到以下错误。我无法添加公共构造函数,因为这会导致SimpleInjector发生错误。

No parameterless constructor defined for this object. 

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.MissingMethodException: No parameterless constructor defined for this object. 

Source Error: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. 

Stack Trace: 


[MissingMethodException: No parameterless constructor defined for this object.] 
    System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0 
    System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +113 
    System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +232 
    System.Activator.CreateInstance(Type type, Boolean nonPublic) +83 
    System.Activator.CreateInstance(Type type) +66 
    System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +110 

[InvalidOperationException: An error occurred when trying to create a controller of type 'my.project.Web.Controllers.MyController'. Make sure that the controller has a parameterless public constructor.] 
    System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +247 
    System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +438 
    System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +257 
    System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +328 
    System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +157 
    System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +88 
    System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +50 
    System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301 
    System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155 

如果有人能指出我正确的方向,那会很好。

回答

18

之所以得到这个错误是因为你缺少下列注册(如MVC integration guide解释):

DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container)); 

MVC和Web API都必须解决的依赖自己的抽象(均称为“依赖解析“)。由于您没有为MVC设置解析器,因此MVC使用默认解析机制来创建MVC控制器,但这需要控制器具有默认构造器。

调用DependencyResolver.SetResolver将解决该问题。

+0

谢谢,现在完美的工作 – Gillardo 2014-09-22 13:50:39

+0

OMG我已经花了大约5个小时对此。谢谢救星。 – 2017-03-07 17:26:12

2

对于Web API项目,上面描述的SetResolver方法将编译,但是当应用程序运行时,您将得到一个ArgumentException错误:“其他信息:类型SimpleInjector.Integration.WebApi.SimpleInjectorWebApiDependencyResolver不会实现Microsoft .Practices.ServiceLocation.IServiceLocator“。

您将通过将DependencyResolver设置为SimpleInjectorWebApiDependencyResolver并传入容器来解决此问题,如下所示。

GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container); 
相关问题