我使用了WebForms(旧版)+ ASP.NET MVC + SimpleInjector
public abstract class CustomBaseController : Controller
{
protected User user;
protected IAppDbContext repo;
public CustomBaseController(User user, IAppDbContext repo)
{
this.user = user;
this.repo = repo;
}
}
// my controller
[MyCustomAuthorize]
public class MyCustomController : CustomBaseController
{
public MyCustomController(User user, IAppDbContext repo) : base(user, repo)
{
}
[HttpPost]
public ActionResult PostMethod()
{
user.Name = "NewUserName"; // throw NullReferenceException that user is null
// some logic
// some logger
}
}
// user entity
public class User
{
public Guid Id { get; protected set; }
public string Email { get; protected set; }
public string DisplayName { get; protected set; }
public string FirstName { get; protected set; }
public string LastName { get; protected set; }
// and other properties
}
// Register DI
private static void InitializeContainer()
{
var container = new Container();
container.Register<IUserSessionManagement, UserSessionManagement >(Lifestyle.Scoped);
container.Register<User>(() => container.GetInstance<UserSessionManagement>().UserSession, Lifestyle.Scoped);
DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
}
// Wrapper for User
public class UserSessionManagement : IUserSessionManagement
{
public User UserSession { get; }
public UserSessionManagement(IAppDbContext repo)
{
UserSession = (HttpContext.Current.Session[SESSION_AUTHENTICATED_USER] as User) ?? new User(Guid.Empty, null, null);
}
}
我在user
请求中捕获了NullReferenceException(/PostMethod
为空)。
我一直在寻找可以删除参考资料的任何地方。没有。参考无法重写。看来GC已清除所有链接。
注意:我无法在调试中重现此内容。我从日志中知道了这个问题。
注意1:MyCustomController
创建成功(user
不为空)。
发布请求以期望用户为空。
答案 0 :(得分:-1)
看看这个答案Here
我们必须查看您的CustomBaseController才能查看更多。
public MyCustomController() : base()
{
}
您可能只需要一个无参数的构造函数。