簡體   English   中英

溫莎城堡-沒有為此對象定義無參數的構造函數

[英]castle windsor - No parameterless constructor defined for this object

我的主項目中有FileHandler.ashx文件。

public class FileHandler : IHttpHandler
{
    private readonly IAccountService _accountService;
    private readonly IAttachmentService _attachmentService;


    public FileHandler(IAccountService accountService, IAttachmentService attachmentService)
    {
        _accountService = accountService;
        _attachmentService = attachmentService;
    }

  ....
}

另外,我有HandlerInstaller

public class HandlersInstaller : IWindsorInstaller
{

    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(Classes.FromThisAssembly()
                        .Where(Component.IsInSameNamespaceAs<FileHandler>())
                        .WithService.DefaultInterfaces()
                        .LifestyleSingleton());

    }
}

但是,當我嘗試調用FileHandler.ashx文件時,出現錯誤:

沒有為此對象定義無參數構造函數。

是什么原因? 如何解決?

我認為您必須提供一個空的承包商

public class FileHandler : IHttpHandler
    {
        private readonly IAccountService _accountService;
        private readonly IAttachmentService _attachmentService;

        public FileHandler()
        {
        }
        public FileHandler(IAccountService accountService, IAttachmentService attachmentService)
        {
            _accountService = accountService;
            _attachmentService = attachmentService;
        }

      ....
    }

溫莎城堡可能無法解決您當前構造函數需要IAccountServiceIAttachmentService的依賴IAttachmentService

在這種情況下,可能正在尋找一種無參數的替代方法。

確保已注冊上述依賴項,並且Windsor可以解決它們。

在您的web.config中,您有以下內容:

  <castle>
    <installers>
      <install type="Your.Namespace.HandlersInstaller, Your.Namespace" />
    </installers>
  </castle>

溫莎城堡不知道如何創建IHttpHandler實例。 沒有類似ControlerFactory的處理程序,因此您無法攔截處理程序的創建過程。 您有兩種選擇:

  1. 將處理程序實現為控制器操作,並使用標准的WindsorControlerFactory注入依賴項。
  2. 使用Windsor作為服務定位器,提供較少參數的構造函數:

     public class FileHandler : IHttpHandler { readonly IAccountService accountService; readonly IAttachmentService attachmentService; public FileHandler() { var containerAccessor = HttpContext.Current.ApplicationInstance as IContainerAccessor; var container = conatinerAccessor.Container; accountService = container.Resolve<IAccountService>(); attachmentService = container.Resolve<IAttachmentService>(); } public FileHandler(IAccountService accountService, IAttachmentService attachmentService) { this.accountService = accountService; this.attachmentService = attachmentService; } ... } 

查看此答案以了解如何實現IContainerAccessor

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM