C# 组件已注册,但也在等待依赖项

C# 组件已注册,但也在等待依赖项,c#,dependency-injection,castle-windsor,C#,Dependency Injection,Castle Windsor,我有一些温莎城堡组件注册,如下所示 container.Register( Component.For<IService>() .Named("proxy-service") .ImplementedBy<ProxyService>() .DependsOn(Dependency.OnComponent( typeof(IHttpClient), "backend-http-client"))

我有一些温莎城堡组件注册,如下所示

container.Register(
    Component.For<IService>()
        .Named("proxy-service")
        .ImplementedBy<ProxyService>()
        .DependsOn(Dependency.OnComponent(
            typeof(IHttpClient), "backend-http-client")),
    Component.For<IHttpClient>()
        .Named("backend-http-client")
        .ImplementedBy<DefaultHttpClient>()
        .DependsOn(Dependency.OnAppSettingsValue(
            "baseAddress", "backendServerBaseAddress"))
);
container.Register(
用于()的组件
.Named(“代理服务”)
.由()实施
.DependsOn(Dependency.OnComponent(
类型(IHttpClient),“后端http客户端”),
用于()的组件
.Named(“后端http客户端”)
.由()实施
.Dependenson(Dependency.OnAppSettingsValue(
“baseAddress”、“backendServerBaseAddress”))
);
  • ProxyService
    实现
    IService
    ,并具有一个构造函数,该构造函数接受单个
    IHttpClient

  • DefaultHttpClient
    实现
    IHttpClient
    ,并具有一个构造函数,该构造函数接受一个名为
    baseAddress
    字符串

现在,如果我试图通过调用
container.Resolve(“代理服务”)
来测试我的注册,我会得到以下异常

Castle.MicroKernel.Handlers.HandlerException:无法创建组件“代理服务”,因为它需要满足依赖关系

“代理服务”正在等待以下依赖项:
-组件“后端http客户端”(通过覆盖),该组件已注册,但也在等待依赖项

奇怪的是,以下两项都起作用

  • container.Resolve(“后端http客户端”)
  • 切换
    “代理服务”
    “后端http客户端”
    注册的顺序
  • 我在这里真的很困惑,因为我经常使用温莎城堡,从来没有遇到过这样的问题,这显然不是由于注册中的打字错误或错误造成的

    为什么上面的(1)行得通,但解析仅依赖于它的组件却不行

    为什么(2)让它工作?注册的顺序应该无关紧要,除非同一个接口有多个注册(在我的案例中没有)。我为其他项目编写了代码,这些项目通过许多不同的注册完成了相同的工作


    是否有明显的错误,我错过了?

    问题是,我的小测试是在安装之前在安装程序内部运行的

    我的安装程序如下所示:

    class WindsorInstaller : IWindsorInstaller
    {
        void IWindsorInstaller.Install(IWindsorContainer container, IConfigurationStore store)
        {
            container.Register(...);
    
            //A little one-time test to try out the resolving of the service.
            //It would be removed as soon as it works.
            var service = container.Resolve<IService>("proxy-service");
        }
    }
    
    container = new WindsorContainer().Install(new WindsorInstaller());
    

    所以在安装之前调用了
    Resolve
    。当然,一旦我将测试调用移动到
    Resolve
    ,这样它就会在调用
    Install
    之后发生,一切都正常了。

    在我的例子中,问题是我注册了
    IService
    ,但试图在顶级依赖对象的构造函数中解析
    服务

    public class MyController : Controller
    {
        private readonly IService _service;
    
        public MyController(Service service) //problem here, Iservice should be used instead
        {
            _service = service;
        }
    }