我的目标是在并行线程中运行永无止境的进程。问题是,我不能仅在新线程中实例化我的辅助服务,因为我在应用程序中使用了DI。
根据我在SO上的研究,我注意到许多人建议将抽象工厂注入线程中,以便在并行线程中动态实例化线程安全对象。1,2
/// <summary>
/// Responsible for starting parallel long running worker threads
/// </summary>
public class ParallelWorkerStarter
{
private readonly IQueueProcessorFactory _queueProcessorFactory;
public ParallelWorkerStarter(IQueueProcessorFactory queueProcessorFactory)
{
_queueProcessorFactory = queueProcessorFactory;
}
public void StartQueueProcessorThread()
{
queueProcessor = new Thread(
() =>
{
_queueProcessorFactory.Create().ProcessQueue();
})
{ Name = "QueueProcessor" };
queueProcessor.Start();
}
}
的Abstract FactoryIQueueProcessorFactory看起来像这样:
/// <summary>
/// Abstract factory responsible for producing an <see cref="IQueueProcessor"/>
/// </summary>
/// <remarks>
/// This abstract factory is used to generate an <see cref="IQueueProcessor"/> In a seperate thread.
/// Therefore, all of its dependencies also need to be dynamically generated
/// </remarks>
public interface IQueueProcessorFactory
{
/// <summary>
/// Dynamically creates ab <see cref="IQueueProcessor"/>
/// </summary>
/// <returns>
/// The <see cref="IQueueProcessor"/>.
/// </returns>
IQueueProcessor Create();
}
现在,我的主要问题是,QueueProcessor实现的具体对象IQueueProcessor具有11个依赖项(我知道SRP代码的味道),每个依赖项本身都有5-6个依赖项。
这是否意味着我需要约60多个抽象工厂才能IQueueProcessor
在工作线程中实例化我?这听起来像一场噩梦!是否有更好的方法或更有效的方法来实现这一目标?
慕丝7291255
相关分类