Injecting dependencies in Global.asax does not seem to always work. Sometimes it does, sometimes I get a ContextDisposedException (it seems that the problem occurs when I'm doing a Page.Redirect ??). I'm in an ASP.NET WebForm context.
Here is my code:
public class Global : HttpApplication
{
[Inject]
public UserManager UserManager { get; set; }
private void Application_PostAuthenticateRequest(object sender, EventArgs e)
{
if (User.Identity.IsAuthenticated)
{
GlobalSecurityContext.SetPrincipal(User);
string path = Request.AppRelativeCurrentExecutionFilePath;
if (path.Contains(".aspx"))
{
// Get the current user
var userData = UserManager.GetByIdWithLogin(User.Identity.Name);
if (userData != null)
{
LoginDataDTO data = userData.LoginData;
if (data.XXX && ...)
{
Response.Redirect(...);
}
}
}
}
}
protected void Session_End(Object sender, EventArgs e)
{
UserManager.Logout();
}
}
In this post How to inject dependencies into the global.asax.cs, Mark Seemann says that one should not use Dependency Injection in global.asax because global.asax IS the Composition Root.
So what is the best way to solve my problem since I don't want to directly call my UserManager because the constructor needs a repository
public UserManager(IGenericRepository repository) : base(repository)
{
}
and the GenericRepository
has itself a constructor that needs a IContext
public GenericRepository(IContext context)
{
}
I could probably do new UserManager(new GenericRepository(new MyContext))
but
- I will not reuse the same context for the whole request
- I need to add a reference on my AccessLayer in the GUI, what I would like to avoid
Just as an information, currently I'm injecting the Context like this:
// Dynamically load the context so that we dont have a direct reference on it!
string contextType = // read type from web.config
if (!String.IsNullOrEmpty(contextType))
{
Type context = Type.GetType(contextType);
Bind<IContext>().To(context).InRequestScope();
}
Any help would be greatly appreciated !
[Edit]:
Changing the UserProperty property like this works:
public UserManager UserManager
{
get { return ServiceLocator.Current.GetInstance<UserManager>(); }
}