尝试创建类型的控制器时发生错误 'ChatBotController'。确保控制器有一个 无参数的公共构造函数。
在System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage 请求,HttpControllerDescriptor controllerDescriptor,类型 controllerType)↵在 System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage 要求)↵ System.Web.Http.Dispatcher.HttpControllerDispatcher.d__15.MoveNext()
当我尝试到达IFeedbackRepository时,我得到了错误的提示。当我在ChatBotController.cs中放入构造函数时,就会发生这种情况
public class ChatBotController : ApiController
{
IFeedbackRepository _feedbackRepository;
public ChatBotController(IFeedbackRepository feedbackRepository)
{
_feedbackRepository = feedbackRepository;
}
[HttpPost]
public IHttpActionResult PostQuestion([FromBody]string message) //TODO: make sure that webapi will search the message in the body of the http request
{
throw new NotImplementedException();
}
}
我同时使用MVC和Api,它们都在Global.asax中解析:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
DependencyConfig.RegisterWebApiDependencies();
DependencyConfig.RegisterMvcDependencies();
}
这是我对MVC和Api的DependencyConfig.cs:
public static void RegisterWebApiDependencies()
{
var container = new Container();
container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();
container.Register<IAnswerGenerator, PxlAnswerGenerator>(Lifestyle.Scoped);
container.Register<ChatBotDbContext>(Lifestyle.Scoped);
container.Register<IFeedbackRepository, FeedbackDbRepository>(Lifestyle.Scoped);
container.Verify();
DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
}
public static void RegisterMvcDependencies()
{
var container = new Container();
container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();
container.Register<IFeedbackRepository, FeedbackDbRepository>(Lifestyle.Scoped);
container.Register<ChatBotDbContext>(Lifestyle.Scoped);
container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
container.Verify();
DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
}
我在做什么错了?
答案 0 :(得分:2)
根据documentation of Simple-Injector,当您要为注册的WebApi部分初始化解析器时,需要调用
container.RegisterWebApiControllers(GlobalConfiguration.Configuration);
container.Verify();
DependencyResolver.SetResolver(new SimpleInjectorWebApiDependencyResolver(container));
答案 1 :(得分:0)
我看不到您在调用container.RegisterWebApiControllers(GlobalConfiguration.Configuration);在RegisterWebApiDependencies()中。这是必需的。
您可能希望在此处查看用于与ASP.NET Web API和MVC集成的simpleinjector文档:
https://simpleinjector.readthedocs.io/en/latest/webapiintegration.html
此外,以上文档在application_start()的开头具有容器/ DI设置。如果仅上述更改不起作用,则可能要尝试将以下两行放在application_start()的开头:
DependencyConfig.RegisterWebApiDependencies(); DependencyConfig.RegisterMvcDependencies();