代码之家  ›  专栏  ›  技术社区  ›  Simon Keep

Is it ok to register components in Windsor without specifying an interface?

  •  15
  • Simon Keep  · 技术社区  · 16 年前

    Is it considered bad form to register components in Windsor without specifying an interface? 即

    container.Register(Component.For<MyClass>().LifeStyle.Transient);
    

    与…相反

    container.Register(Component.For<IMyClass>().ImplementedBy<MyClass>().LifeStyle.Transient);
    

    我理解编码到一个接口而不是具体实现的好处,但是我们发现我们现在有很多接口,其中很多都在类上,实际上只有一个实现。

    1 回复  |  直到 7 年前
        1
  •  25
  •   Krzysztof Kozmic    16 年前

    是的,在没有接口的情况下注册组件是可以的。 not for the reason you give .

    Concrete dependencies

    It may happen that components depend on concrete classes. For instance, with the Entity Framework consumers should have the ObjectContext injected into them. That's a concrete class that still needs to be injected because it should be 共享 between several consumers.

    Thus, given a consumer's constructor like this:

    public FooRepository(FooObjectContext objectContext)
    

    you would need to configure the container like this:

    container.Register(Component.For<FooObjectContext>());
    

    前驱力 requests no interface so it makes no sense registering an interface (even if one was available), but you must still register the concrete class because Windsor can only resolve types explicitly registered .

    Interfaces with only one implementation

    那么只有一个实现的接口呢?消费者再次决定需求。

    Imagine that a consumer has this constructor:

    public Ploeh(IBar bar)
    

    温莎城堡解决普洛伊问题的唯一方法就是注册IBAR。即使BAR是IBAR的唯一实现, this will not work :

    container.Register(Component.For<Bar>());
    

    这不起作用,因为IBAR从未注册过。温莎城堡不在乎酒吧实施IBAR,因为它不想为你变聪明。你必须明确地告诉它:

    container.Register(Component.For<IBar>().ImplementedBy<Bar>());
    

    这个 地图 Ibar酒吧。

    Registering both interfaces and concrete types

    Then what if you want to be able to resolve both the concrete type and the interface?

    前一个示例的问题是它将允许您解决IBAR,而不是BAR。

    You can use the Forward method, or multigeneric overload of For to forward registrations:

    container.Register(Component.For<Bar, IBar>().ImplementedBy<Bar>());
    

    This lets you resolve 二者都 酒吧和伊巴尔河。