依赖注入到global.asax
本文关键字:asax global 注入 依赖 | 更新日期: 2023-09-27 18:15:44
在全局中注入依赖。Asax似乎并不总是有效。有时确实如此,有时我得到一个ContextDisposedException(似乎问题发生时,我正在做一个页面。重定向? ?)。我在一个ASP。. NET WebForm context.
下面是我的代码: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();
}
}
在《如何在global.asax.cs中注入依赖》一文中,Mark Seemann说不应该在global中使用依赖注入。因为全球化。asax是组合根。
那么解决这个问题的最好方法是什么呢?因为我不想直接调用我的UserManager,因为构造函数需要一个存储库
public UserManager(IGenericRepository repository) : base(repository)
{
}
和GenericRepository
本身有一个需要IContext
public GenericRepository(IContext context)
{
}
我可以用new UserManager(new GenericRepository(new MyContext))
,但是
- 我不会在整个请求中重用相同的上下文
- 我需要在GUI中添加一个对我的AccessLayer的引用,我想避免
就像一个信息,目前我像这样注入上下文:
// 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();
}
任何帮助都将是非常感激的!
[编辑]:
像这样改变UserProperty属性:
public UserManager UserManager
{
get { return ServiceLocator.Current.GetInstance<UserManager>(); }
}
在这种情况下,你可以构建你的Ninject容器,并使用它作为这个特定实例的服务定位器(因为你在Composition根目录中——此时你不能注入任何东西)