【问题标题】:Structuring Dependency Injection for a Class with Injected Services AND Data为具有注入服务和数据的类构建依赖注入
【发布时间】:2010-11-29 11:25:25
【问题描述】:

我正在使用一个使用构造函数注入的 IoC 容器(例如,Castle Windsor)。我有以下管理产品的(示例)类...

public class ProductDataManager
{
    public ProductDataManager(Product product, IProductDataLoader productDataLoader)
    {
    }

    // a number of methods here that manage the products data in different ways...
}

它依赖于只有类消费者知道的产品。它还依赖于产品数据加载器服务。我在 IoC 容器中定义了这个服务的实现者。

如何在 IoC 容器(和/或消费类)中定义此类(ProductDataManager),以便 IoC 容器可以注入服务依赖项(IProductDataLoader),而数据依赖项(Product)可以被消费类传递?

或者这是代码异味?如果是这样,如何修改?

【问题讨论】:

    标签: dependency-injection castle-windsor ioc-container


    【解决方案1】:

    您可以使用TypedFactoryFacility 并执行类似的操作(在我的脑海中)...首先,为您的抽象工厂定义一个接口:

    public interface IProductDataManagerFactory
    {
        ProductDataManager Create(Product product);
    }
    

    像这样注册工厂:

    container.AddFacility<TypedFactoryFacility>();
    container.Register(Component.For<IProductDataManagerFactory>().AsFactory());
    

    现在服务可以依赖 IProductDataManagerFactory 并让 Windsor 通过自动实现的工厂调用 container.Resolve

    注意方法签名中的参数名product必须与ProductDataManager的ctor中的参数名对应。

    【讨论】:

    • 如果工厂是一个简单的 new() 那么我想说甚至不需要创建接口,注入 Func 没有任何问题。你甚至可以使用一个花哨的工具来做到这一点:mikehadlow.blogspot.com/2010/01/…
    • @Mark:虽然创建IXXXFactory 更加冗长,但它更加明确并且使您的代码更容易被工厂理解。在我看来,使用Func&lt;Product, ProductDataManager&gt; 有点神秘。
    猜你喜欢
    • 1970-01-01
    • 2020-09-09
    • 2019-09-06
    • 1970-01-01
    • 1970-01-01
    • 2020-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多