【发布时间】:2012-07-30 18:08:38
【问题描述】:
我想注入构造函数参数 IActionLogger actionLogger,但希望其他参数 largeBucket、smallBucket 和 amountToRetrieve 是上下文相关的(不确定这是否正确)。
问题:
我是否应该将这些构造函数参数设为自动属性,并将 IActionLogger actionLogger 参数留在构造函数中?
基本上,计算会根据 largeBucket、smallBucket 和 amountToRetrieve 变量而有所不同? 我将这些变量放在构造函数中,因为我需要事先进行一些设置。
public class BucketActionsHandler : IBucketActionsHandler
{
private List<IAction> _actions = new List<IAction>();
private Bucket _largeBucket;
private Bucket _smallBucket;
private IActionLogger _actionLogger;
private int _amountToRetrieve;
public BucketActionsHandler(Bucket largeBucket, Bucket smallBucket, int amountToRetrieve, IActionLogger actionLogger)
{
_largeBucket = largeBucket;
_smallBucket = smallBucket;
_amountToRetrieve = amountToRetrieve;
_actionLogger = actionLogger;
_actions.Add(new LastAction(largeBucket, smallBucket, amountToRetrieve));
_actions.Add(new EmptySmallerBucketAction(largeBucket, smallBucket, amountToRetrieve));
_actions.Add(new EmptyLargeBucketAction(largeBucket, smallBucket, amountToRetrieve));
_actions.Add(new FillLargeBucketAction(largeBucket, smallBucket, amountToRetrieve));
_actions.Add(new FillSmallBucketAction(largeBucket, smallBucket, amountToRetrieve));
_actions.Add(new TransferToLargeBucketAction(largeBucket, smallBucket, amountToRetrieve));
_actions.Add(new TransferToSmallBucketAction(largeBucket, smallBucket, amountToRetrieve));
}
private IAction GetNextAction()
{
foreach (var action in _actions)
{
if (action.SatisfiedCondition())
{
return action;
}
}
return null;
}
public void CalculateSteps()
{
IAction nextAction;
do
{
nextAction = GetNextAction();
nextAction.Execute();
if (nextAction == null)
{
throw new InvalidOperationException("No valid action available");
}
} while(!(nextAction is LastAction));
}
}
【问题讨论】:
-
你好,如果你的 BucketActionsHandle 是完全用 IActionLogger 构造的,你可以通过构造函数注入 IActionLogger。其他参数是变量,如果它们在运行时发生变化,你不必注入它们。如果它们是设置一次通过属性注入它们
标签: c# dependency-injection unity-container ninject-2 constructor-injection