我想知道,如果创建标记虚拟类(内部没有成员)只是为了在通用签名中使用是一个好主意或不是。
例如,考虑下面的界面签名:
public interface IBusinessValidatorFor<TContext, TEntity>
where TContext : IContext
{
IList<ValidationStatus> Validate (TEntity entityToValidate);
}
实现上述接口的示例具体类可以是:
public sealed class BusinessValidatorFor<CreationContext, Customer>
: IBusinessValidatorFor<CreationContext, Customer>
{
public IList<ValidationStatus> Validate (Customer customerToValidate)
{
// Creation of customer related business validation code here.
}
}
在上面的具体类定义中,类 CreationContext (实现标记接口 IContext )是一个没有属性的虚拟类,但仅用于区分它来自同一Customer类的其他验证器,但适用于不同的其他上下文。
这种做法是个好主意吗?有没有比使用虚拟无成员空类更好的设计选择?
上述设计的目的是允许为同一实体创建多个验证器具体类,但对于各种上下文,并将其与依赖注入容器一起使用。
以下代码显示了针对各种上下文的此类验证程序的用法:
public sealed class CustomerController
: Controller
{
private readonly IBusinessValidatorFor<CreationContext, Customer>
custCreateValidator;
private readonly IBusinessValidatorFor<ModificationContext, Customer>
custModifyValidator;
public CustomerController
(
IBusinessValidatorFor<CreationContext, Customer> custCreateValidator,
IBusinessValidatorFor<ModificationContext, Customer> custModifyValidator,
)
{
this.custCreateValidator = custCreateValidator;
this.custModifyValidator= custModifyValidator;
}
public ActionResult Create (Customer customerToCreate)
{
var results = this.custCreateValidator.Validate (customerToCreate);
...
}
public ActionResult Modify (Customer customerToModify)
{
var results = this.custModifyValidator.Validate (customerToModify);
...
}
}
非常感谢您的时间和帮助!