如何将参数传递给通过IoC容器关联其依赖项的类? [英] How to pass parameter to a class whose dependencies are wired through IoC container?
问题描述
我有一个可以通过多种资源与网络配合使用的类.它的构造函数接收在运行时由IoC容器(StructureMap)解析的参数:
I have a class that works with a network via multiple resources. Its constructor receives arguments that are resolved at runtime by IoC container (StructureMap):
public NetworkWorker(IRetryService retryService, ILog log)
{ ... }
我需要的是在用例级别上控制此类使用的资源数量-例如,客户端A需要一次仅允许一次操作的NetworkWorker实例,而客户端B一次需要10个操作.
当前,此数字在构造函数中进行了硬编码.我看到的唯一方法是添加一个void Configure(int resourceCount)
方法,NetworkWorker的每个客户端都将使用不同的值来调用该方法.
或者有没有更好的方法我看不到?
该类可以做不同的事情,但是每个方法调用(Get/Send/etc
方法)都需要一定数量的资源.
P.S.这是已知技术(使用Configure
方法)吗?如果是,它的名字是什么?像两步初始化"一样吗?
What I need is to control the number of resources this class uses on a use-case level - for example, client A need NetworkWorker instance that allows only one operation at a time, while client B need 10 ops at a time.
Currently this number is hardcoded in the constructor. The only way I see is to add a method void Configure(int resourceCount)
that each client of NetworkWorker would call with a different value.
Or may be there's a better way I don't see?
This class can do different things, but number of resources is required for every method call (Get/Send/etc
methods).
P.S. is this a known technique (with a Configure
method)? If it is, what's the name for it? smth like 'two-step initialization'?
推荐答案
我假设此NetworkWorker具有多个方法(否则,您可以仅向该单个方法添加参数).
I'll presume this NetworkWorker has multiple methods (otherwise you could just add a parameter to that single method).
您可以使用工厂模式:
You could use a factory pattern:
public interface INetworkWorkerFactory
{
NetworkWorker Create(int numberOfResources);
}
public class NetworkWorkerFactory : INetworkWorkerFactory
{
private readonly IContainer _container;
public NetworkWorkerFactory(IContainer container)
{
_container = container;
}
public NewtorkWorker Create(int numberOfResources)
{
var retryService = _container.GetInstance<IRetryService>();
var log = _container.GetInstance<ILog>();
return new NewtorkWorker(retryService, log, numberOfResources);
}
}
(或简单地注入所需的依赖项而不是容器) 然后简单地
(or simply inject the required dependencies instead of the container) and then simply
private readonly INetworkWorkerFactory _networkWorkerFactory;
public C(INetworkWorkerFactory networkWorkerFactory)
{
_networkWorkerFactory = networkWorkerFactory;
}
public void M()
{
var networkWorker = _networkWorkerFactory.Create(10);
}
这篇关于如何将参数传递给通过IoC容器关联其依赖项的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!