Ошибка публичного конструктора параметров - PullRequest
0 голосов
/ 25 августа 2018

Произошла ошибка при попытке создать контроллер типа 'ChatBotController'.Убедитесь, что в контроллере есть открытый конструктор без параметров.

в System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create (запрос HttpRequestMessage, HttpControllerDescriptor controllerDescriptor, тип controllerType) ↵ в System.WontrollerHT..CreateController (HttpRequestMessage request) в 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();
}

Thisмой DependencyConfig.cs для MVC и Api:

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

Что я делаю не так?

Ответы [ 2 ]

0 голосов
/ 25 августа 2018

Я не вижу, чтобы вы вызывали container.RegisterWebApiControllers (GlobalConfiguration.Configuration); в RegisterWebApiDependencies (). Это необходимо.

Вы можете просмотреть документацию по простым инжекторам для интеграции с ASP.NET Web API и MVC здесь:

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

Также в документации выше есть настройка контейнера / DI в начале application_start (). Если указанное выше изменение не работает, вы можете попробовать поместить следующие две строки в начало application_start ():

DependencyConfig.RegisterWebApiDependencies (); DependencyConfig.RegisterMvcDependencies ();

0 голосов
/ 25 августа 2018

В соответствии с документацией Simple-Injector , если вы хотите инициализировать распознаватель для части вашей регистрации через WebApi, вам нужно позвонить

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