Reputation: 303
I used WebForms (legacy) + 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);
}
}
I catch NullReferenceException (user
is null) on /PostMethod
request.
I was looking for any place where the reference could wipe. Nothing. Reference cannot rewrite. it looks like GC has cleaned all the links.
NOTE: I cannot reproduce this in debugging. I know about this problem from the logs.
NOTE1: MyCustomController
created successful (user
is not null).
Post request to throw expection that user is null.
Upvotes: 0
Views: 75
Reputation: 2599
Take a look at this answer Here
We would have to see your CustomBaseController To see more.
public MyCustomController() : base()
{
}
You may just need a parameterless constructor.
Upvotes: -1