我對使用IOC容器還有點新意,而且我正在努力一點。我正在使用ASP.NET MVC 5.2與Ninject.MVC3。我有一個異常過濾器,基本上丟給日誌服務:如何在ASP.NET MVC的RegisterGlobalFilters方法中執行依賴注入
public class ExceptionLoggerFilter : IExceptionFilter
{
private readonly ILogService _logService;
public ExceptionLoggerFilter(ILogService logService) {
_logService = logService;
}
public void OnException(ExceptionContext filterContext) {
_logService.LogError(filterContext.Exception);
}
}
我想使用依賴注入來獲取日誌服務的實例。然而,RegisterGlobalFilters方法是靜態的:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new ExceptionLoggerFilter(???));
}
}
我可以用一個靜態構造函數的一個FilterConfig,但這只是不覺得自己是一個很好的解決方案。
我嘗試使用性能噴射在ExceptionLoggerFilter類,但它只是沒有工作(LogService總是空):
[Inject]
public ILogService LogService { get; set; }
我已經在使用工廠模式讀了,但事實並非如此似乎在這裏幫助,因爲我仍然需要將Factory類注入到FilterConfig類的靜態構造函數中。我可能是錯的,但是這也不是正確的解決方案。
var logService = (ILogService)DependencyResolver.Current.GetService(typeof(ILogService));
filters.Add(new ExceptionLoggerFilter(logService));
這工作,但它是一個很好的解決方案:
現在,我使用的是剛剛放棄的我,一個實例方法?有沒有更好的辦法?我對依賴注入和IOC容器的想法都搞砸了嗎?
這樣做通常是一個壞主意,除非您確定知道'IExceptionFilter'註冊(及其所有依賴項)ar因爲MVC全局過濾器是全局存儲的,這意味着它們變成了單例。 – Steven