【问题标题】:Simple Injector and routeattribute webapi简单的注入器和路由属性 web api
【发布时间】:2015-08-12 15:39:20
【问题描述】:

我有一个 WebApi 2 应用程序,我正在使用简单的注入器,一切正常。

但是今天我尝试使用 [RoutePrefix] 和 [Route] 属性来解析特定控制器上的路由,似乎简单的注入器无法创建我的控制器的实例。

我收到了这个错误

尝试创建类型控制器时出错 '新控制器'。确保控制器具有无参数 公共构造函数。类型 'Public.API.Controllers.NewController' 没有默认值 构造函数

堆栈跟踪:

at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType) 
at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request) 
at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()

at System.Linq.Expressions.Expression.New(Type type) 
at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType) 
at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator) 
at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)

我的控制器是这样的

[Authorize]
[RoutePrefix("api/New")]
public class NewController : ApiController
{
    private IUserService userService;
    public NewController(IUserService userService)
    {
        this.userService = userService;
    }

    [HttpPost]
    [AllowAnonymous]
    public async Task<IHttpActionResult> Register(ApiRegisterUserRequestModel model) {
        return Content(HttpStatusCode.OK, "reponse");
    }

    [HttpPost]
    [AllowAnonymous]
    [Route("ForgotPasswordSendEmail")]
    public async Task<IHttpActionResult> ForgotPasswordSendEmail(
        [FromBody] ApiForgotPasswordRequestModel model)
    {
        var response = "cool";
        return Content(HttpStatusCode.OK, response);
    }
}

如果我向Register 操作发出请求,我会收到响应,但如果我向ForgotPasswordSendEmail 操作发出请求,则会收到上面提到的错误。

我拥有的简单注射器配置是这里提到的基本设置

https://simpleinjector.readthedocs.org/en/latest/webapiintegration.html

更新 我正在使用OWINJWT 令牌身份验证,我的项目中有一个global.asax 和一个startup 文件,并且两者都配置为使用webapi。

这些是我的Startup 班级和Application_Start

//startup class
public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        SimpleInjectorWebApiInitializer.Initialize();
        HttpConfiguration httpConfig = new HttpConfiguration();

        ConfigureOAuthTokenGeneration(app);
        ConfigureOAuthTokenConsumption(app);

        WebApiConfig.Register(httpConfig);

        app.UseWebApi(httpConfig);
    }
}

//Application_Start
protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    GlobalConfiguration.Configure(WebApiConfig.Register);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
    SimpleInjector.Configure();
    SimpleInjectorWebApiInitializer.Initialize();
}

我从startup中删除了所有的api配置,如果这样就离开了

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        ConfigureOAuthTokenGeneration(app);
        ConfigureOAuthTokenConsumption(app);
    }
}

它开始起作用了。

现在,为什么它不能使用[Route] 属性而没有它一切都很好?这对我来说是个谜。

【问题讨论】:

    标签: asp.net-web-api dependency-injection routes asp.net-web-api2 simple-injector


    【解决方案1】:

    我一直在尝试重现此问题,但没有成功。如果注册的 IDependencyResolver.GetService 返回 null 并且请求的类型没有默认构造函数,您通常会收到“确保控制器具有无参数的公共构造函数”错误。

    如果你如你所说,关注Simple Injector's configuration guidanceSimpleInjectorWebApiDependencyResolver 将不会返回null,但会返回一个有效的控制器实例 - 或者 - 将抛出一个表达异常。默认指导说明您至少要做到以下几点:

    container.RegisterWebApiControllers(GlobalConfiguration.Configuration);
    
    container.Verify();
    
    GlobalConfiguration.Configuration.DependencyResolver =
        new SimpleInjectorWebApiDependencyResolver(container);
    

    如果您使用此代码,则不太可能出现“确保控制器具有无参数的公共构造函数”错误。尤其是在使用一个动作调用时控制器可以被解析,而在另一个动作中初始化失败的情况。

    所以请检查以下内容:

    1. 您正在使用如上所示的代码。
    2. 你确定 api/New/Register 调用实际上是通过NewController。您可以在其构造函数和Register 方法中设置断点。
    3. NewController实际上可以在手动调用container.GetInstance&lt;NewController&gt;()时正确解析。

    【讨论】:

      猜你喜欢
      • 2018-08-23
      • 1970-01-01
      • 1970-01-01
      • 2017-03-24
      • 2016-02-22
      • 1970-01-01
      • 2015-03-29
      • 2014-04-19
      • 2015-07-19
      相关资源
      最近更新 更多