代码之家  ›  专栏  ›  技术社区  ›  Mark Watts

温莎城堡-DependsOn在F#不工作?

  •  1
  • Mark Watts  · 技术社区  · 11 年前

    使用在每次注册的基础上注册依赖项 DependsOn 似乎在F#中不起作用——我是不是错过了什么?

    例如,这将不起作用(解析错误,等待依赖关系 IChild 未注册):

    module Program
    
    open System
    open Castle.Windsor
    open Castle.MicroKernel.Registration
    
    type IChild = 
        interface end
    
    type IParent = 
        interface end
    
    type Child () = 
        interface IChild
    
    type Parent (child : IChild) = 
        interface IParent
    
    [<EntryPoint>]
    let main _ = 
    
        let dependency = Dependency.OnValue<IChild> (Child ())
    
        use container = new WindsorContainer ()
    
        container.Register (
            Component.For<IParent>().ImplementedBy<Parent>().DependsOn(dependency)
        ) |> ignore
    
        let parent = container.Resolve<IParent> () //Exception due to missing dependency
    
        0 
    

    然而,在容器中全局注册类型可以很好地工作,例如。

    module Program
    
    open System
    open Castle.Windsor
    open Castle.MicroKernel.Registration
    
    type IChild = 
        interface end
    
    type IParent = 
        interface end
    
    type Child () = 
        interface IChild
    
    type Parent (child : IChild) = 
        interface IParent
    
    [<EntryPoint>]
    let main _ = 
    
        use container = new WindsorContainer ()
    
        container
            .Register(Component.For<IChild>().ImplementedBy<Child>())
            .Register(Component.For<IParent>().ImplementedBy<Parent>())
        |> ignore        
    
        let parent = container.Resolve<IParent> () //Works as expected
    
        0 
    

    我看不出由 Dependency.OnValue 在C#和F#中。

    1 回复  |  直到 11 年前
        1
  •  1
  •   Mark Watts    11 年前

    正如Mauricio Scheffer所指出的,问题在于 Dependency.OnValue<T> 返回一个Property,F#不会自动使用在Property上定义的隐式转换来调用 DependsOn(Dependency) 。相反,它会调用 DependsOn(obj) 其旨在用于匿名类型。

    更改代码以便像这样创建依赖项可以解决问题:

    let dependency = Property.op_Implicit(Dependency.OnValue<IChild>(Child ()))