Windsor城堡 - 没有为此对象定义的无参数构造函数



我在主要项目中有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的依赖项。

在这种情况下,它可能正在寻找无参数的使用。

确保上述依赖项已注册,并且温莎可以解决它们。

在您的web.config中,您是否有:

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

Castle Windsor不知道如何创建IHttpHandler实例。没有用于处理程序的 ControlerFactory这样的somethig,因此您不能拦截处理程序创建过程。您有两个选择:

  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

最新更新