Pushpendra
Pushpendra

Reputation: 1712

Web api Controller having constructors with parameters as Generic Service Interface

In my Web api project I am having a controller DocumentViewerV1Controller which has a code as:

      /// <summary>
    /// 
    /// </summary>
    /// <param name="documentViewerService"></param>
    public DocumentViewerV1Controller(IDocumentViewerService<HtmlViewInformation> documentViewerService)
    {
        _documentViewerHtmlService = documentViewerService;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="documentViewerService"></param>
    public DocumentViewerV1Controller(IDocumentViewerService<PageImage> documentViewerService)
    {
        _documentViewerImageService = documentViewerService;
    }/// <summary>
    /// Rendering Document as Html
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    [Route(WebApiConfig.RootApiUri + "/v1/viewashtml/{docid}")]
    public string ViewAsHtml(string docId)
    {
        var documentInfo = new DocumentInfo { DocumentName = HostingEnvironment.MapPath("~/Uploads/") + docId };
        var response = _documentViewerHtmlService.RenderDocument(documentInfo, DocumentRenderType.Html);
        return GenerateResponse(response);
    }

When I run my service, make a call and debug the constructor initialization, It doesn't goes through the initialization which makes _documentViewerHtmlService as null, eventually fails returning Null reference Exception.

Is it possible to have service Interface as IDocumentViewerService?

Upvotes: 0

Views: 3309

Answers (1)

Aydin
Aydin

Reputation: 15284

Yes, but you'll need to remove one of the constructors or tell it which one to use.

container.RegisterType<IViewerInformation, HtmlViewerInformation>();
container.RegisterType<IDocumentViewerService<IViewerInformation>, DocumentViewerServce<IViewerInformation>>();

You may / may not also need to initialize some of the constructors which you can do by

container.RegisterType<IDocumentViewerService<IViewerInformation>, DocumentViewerServce<IViewerInformation>>(
    new InjectionConstructor(...));

Upvotes: 1

Related Questions