[英]Dependency Injection into global.asax
在Global.asax中注入依賴項似乎並不總是有效。 有時會發生,有時會得到ContextDisposedException (似乎在執行Page.Redirect時會出現問題?)。 我在ASP.NET WebForm上下文中。
這是我的代碼:
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();
}
}
馬克·西曼(Mark Seemann)在這篇如何將依賴項注入global.asax.cs中的文章中說,不應在global.asax中使用依賴項注入,因為global.asax是組合根 。
那么,解決我的問題的最佳方法是什么,因為我不想直接調用UserManager,因為構造函數需要存儲庫
public UserManager(IGenericRepository repository) : base(repository)
{
}
並且GenericRepository
本身具有需要IContext
的構造函數
public GenericRepository(IContext context)
{
}
我可能可以做new UserManager(new GenericRepository(new MyContext))
但是
作為一種信息,目前我正在像這樣注入Context:
// 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容器,並將其用於該特定實例的服務定位器(由於您位於“合成根目錄”中,因此此時無法注入任何內容)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.