使用注入的服务和数据构建类的依赖注入

发布于 2024-10-05 03:55:55 字数 535 浏览 0 评论 0原文

我正在使用一个使用构造函数注入的 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),以便服务依赖项(IProductDataLoader)可以由 IoC 容器注入,数据依赖项(Product)可以通过消费阶层?

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

I am using an IoC container that uses constructor injection (Castle Windsor, for example). I have the following (example) class which manages a product...

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

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

It has a dependency on a Product which is only known by the classes consumer. It also has a dependency on a product data loader service. I define the implementer of this service in the IoC container.

How do I define this class (ProductDataManager) in the IoC container (and/or the consuming class) so that the service dependency (IProductDataLoader) can be injected by the IoC container and the data dependency (Product) can be passed by the consuming class?

Or is this a code smell? If so, how can this be modified?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

野味少女 2024-10-12 03:55:55

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

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

像这样注册工厂:

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

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

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

You can use the TypedFactoryFacility and do something like this (off the top of my head)... first, define an interface for your abstract factory:

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

Register the factory like so:

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

Now services can depend on IProductDataManagerFactory and have Windsor invoke container.Resolve through an automagically implemented factory.

Note that the parameter name product in the method signature must correspond to the parameter name in the ctor of ProductDataManager.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文