【发布时间】:2011-08-05 11:15:04
【问题描述】:
我有一个需要有 2 个构造函数的命令类。然而, 使用结构映射似乎我只能指定一个构造函数 使用。我现在已经通过子类型化特定的方式解决了这个问题 命令类,每个实现都有自己的 接口和构造函数。就像下面的代码所示。这 ISelectCommand 为 字符串构造函数和 int 构造函数,只是为了 使用结构映射注册两个子类型。
但是,我认为这是一种 hack,我只是想知道为什么不是 结构映射可以通过 作为构造函数的参数传入的类型?那我就可以注册了 SelectProductCommand 作为 ISelectCommand 和 像这样实例化它: ObjectFactory.With(10).Use>(); orObjectFactury.With("testproduct").Use>();
public class SelectProductCommand : ISelectCommand<IProduct>,
ICommand, IExecutable
{
private readonly Func<Product, Boolean> _selector;
private IEnumerable<IProduct> _resultList;
public SelectProductCommand(Func<Product, Boolean> selector)
{
_selector = selector;
}
public IEnumerable<IProduct> Result
{
get { return _resultList; }
}
public void Execute(GenFormDataContext context)
{
_resultList = GetProductRepository().Fetch(context,
_selector);
}
private Repository<IProduct, Product> GetProductRepository()
{
return ObjectFactory.GetInstance<Repository<IProduct,
Product>>();
}
}
public class SelectProductIntCommand: SelectProductCommand
{
public SelectProductIntCommand(Int32 id): base(x =>
x.ProductId == id) {}
}
public class SelectProductStringCommand: SelectProductCommand
{
public SelectProductStringCommand(String name): base(x =>
x.ProductName.Contains(name)) {}
}
附:我知道如何告诉结构映射使用什么构造函数映射,但我的问题是,是否有办法让结构映射根据传递给构造函数的参数选择正确的构造函数(即使用常规方法重载)。
【问题讨论】:
标签: structuremap