我有一个控制器,它继承自一个抽象的安全控制器,它持有一个用户对象,如下所示。构造函数不一致调用
public new User User
{
get
{
if (this.user == null)
{
var id = int.Parse(base.User.Identity.Name, CultureInfo.InvariantCulture);
this.user = this.UserRepository.FindById(id);
}
return this.user;
}
}
每次我做出以下函数的调用我收到一个空例外的this.UserRepository
[UrlRoute(Path = "api/stats/events/visits/accounttype/{idList}")]
[UrlRoute(Path = "api/{idList}/stats/events/visits/accounttype")]
[UrlRouteParameterDefault(Name = "idList", Value = "")]
public virtual ActionResult Vsat(string idList, DateTime? startDate, DateTime? endDate)
{
// get the ids from the url and retrieve a list of events for those user/s
var ids = (from id in idList.Split(',') where !string.IsNullOrEmpty(id) select Convert.ToInt64(id)).ToList();
var allEvents = this.eventRepository.FindForCompanyBetweenDatesForUsers(
this.User.Company.Id, new List<EventType> { EventType.Visit }, startDate, endDate, ids).ToList();
var groupResults = allEvents.GroupBy(x => x.Account.AccountType.Name);
return null;
}
上面虽然我的API构造函数调用安全控制器的像这样
基构造public ApiController(IUserRepository userRepository) : base(userRepository)
{
}
protected SecureController(IUserRepository userRepository)
{
this.UserRepository = userRepository;
}
更奇怪的是页面上还有其他的函数引用this.User并且它们都没有返回null异常。他们击中了安全构造函数,然后是api构造函数,然后是函数。 以上甚小孔径终端功能(只命名为测试目的)打功能,然后在换行
this.user = this.UserRepository.FindById(id);
除了是,如果我把上面有类似的功能,它的工作原理,但新的函数,那么有同样的问题。
编辑
创建一个新的类和功能完美的作品。
public class TestController : SecureController
{
private readonly IEventRepository eventRepository;
public TestController(IUserRepository userRepository, IEventRepository eventRepository) : base(userRepository)
{
this.eventRepository = eventRepository;
}
[UrlRoute(Path = "test/stats/events/visits/accounttype/{idList}")]
[UrlRoute(Path = "test/{idList}/stats/events/visits/accounttype")]
[UrlRouteParameterDefault(Name = "idList", Value = "")]
public virtual ActionResult Vsat(string idList, DateTime? startDate, DateTime? endDate)
{
// get the ids from the url and retrieve a list of events for those user/s
var ids = (from id in idList.Split(',') where !string.IsNullOrEmpty(id) select Convert.ToInt64(id)).ToList();
var allEvents = this.eventRepository.FindForCompanyBetweenDatesForUsers(
this.User.Company.Id, new List<EventType> {EventType.Visit}, startDate, endDate, ids).ToList();
var groupResults = allEvents.GroupBy(x => x.Account.AccountType.Name);
return null;
}
}
您可以将问题分为更简单,可重复的测试用例吗? –
我更新了这篇文章,希望这就是你的意思 – JConstantine
@JLevett我相信这可能只是一个简单的例子,你的基构造器在某些情况下被赋予一个空引用。在'UserRespository'属性设置器上,尝试测试传入的'value'('if(value == null)throw new Exception(“null!why?”);')并抛出一个特定的异常(如果它为null)检查。 –