表示封闭泛型类型的2种类型IQueryHandler

时间:2015-07-16 11:03:06

标签: c# simple-injector

鉴于以下内容: -

public abstract class PriceBookDataViewModelQuery : IQuery<PriceBookDataViewModel>
{
    public bool IsRenewal { get; set; }
    public string Postcode { get; set; }
}


public class PriceBookDataSseElecViewModelQuery : PriceBookDataViewModelQuery
{
}


public class PriceBookDataSseGasViewModelQuery : PriceBookDataViewModelQuery
{
}

public interface IQueryHandler<in TQuery, out TResult> where TQuery : IQuery<TResult>
{
    TResult Handle(TQuery query);
}

在我的容器配置中我有

Container.RegisterManyForOpenGeneric(
  typeof(IQueryHandler<,>), typeof(IQueryHandler<,>).Assembly);

我的查询处理程序是: -

public class PriceBookDataSseElecViewModelHandler :
    IQueryHandler<PriceBookDataViewModelQuery, PriceBookDataViewModel>

public class PriceBookDataSseGasViewModelHandler : 
    IQueryHandler<PriceBookDataViewModelQuery, PriceBookDataViewModel>

我收到错误消息:

  

有两种类型代表封闭的泛型类型   IQueryHandler。类型:PriceBookDataSseElecViewModelHandler和   PriceBookDataSseGasViewModelHandler。删除其中一种类型或   使用带有BatchRegistrationCallback委托的重载

我理解为什么会发生这种情况,因为我有两种类型从同一个IQueryHandler继承。但最终我将有大约20个这样的查询将包含相同的属性,以便保持干燥。

除了复制20个查询类的属性外,我还有哪些选项?如何在我的场景中使用BatchRegistrationCallback

1 个答案:

答案 0 :(得分:2)

由于害怕对这个问题感到有点困惑,所以我要说的是:

  

我理解为什么会发生这种情况,因为我有两种类型从同一个IQueryHandler继承。但最终我将有大约20个这样的查询将包含相同的属性,以便保持干燥。

如果您有多个具有相同属性的处理程序,为什么不在抽象类中移出共享属性并定义单独且唯一的处理程序?

有时候我喜欢把“DRY”想成“重复自己”,如果它有效并且易于维护和理解,那么请自己重复一遍。你有10个班级并不重要,因为他们被分成单一的责任。

public abstract class PriceBookDataViewModelQuery  {

    public bool IsRenewal { get; set; }
    public string Postcode { get; set; }   
}

public PriceBookDataSseElecViewModelQuery
    : IQuery<PriceBookDataViewModel>, PriceBookDataViewModelQuery {

    // Extra properties
}

public class PriceBookDataSseGasViewModelQuery
    : IQuery<PriceBookDataViewModel>, PriceBookDataViewModelQuery
{
    // Extra properties
}

// First handler 
public class PriceBookDataSseElecViewModelHandler
    : IQueryHandler<PriceBookDataSseElecViewModelQuery, PriceBookDataViewModel>
{
}

// Second handler
public class PriceBookDataSseGasViewModelHandler
    : IQueryHandler<PriceBookDataSseGasViewModelQuery, PriceBookDataViewModel> 
{
}
相关问题