bạn có thể vượt qua HttpContext.Current theo tham số của bộ điều khiển để StaticClass nhưng là một thực hành xấu.
Thực tiễn tốt nhất là trong hàm tạo của Bộ điều khiển nhận giao diện của lớp thực hiện.
private readonly IService _service;
public HomeController(IService service)
{
_service = service;
}
và trong lớp học Dịch vụ
private readonly HttpContextBase _httpContext;
public Service (HttpContextBase httpContext)
{
_httpContext= httpContext;
}
sau đó sử dụng IOC Containner (Ninject, AutoFac vv) cho dependences quyết
dụ trong AutoFac (global.asax)
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterModule(new AutofacWebTypesModule());
builder.RegisterType<Service>().As<IService>().InstancePerLifetimeScope();
Nguồn
2012-01-27 11:11:08
Điều này khiến "Yêu cầu không có sẵn trong lỗi ngữ cảnh này" – oneNiceFriend