我在用ASP.MVC 4
and Autofac
.
我已在我的中注册了以下内容global.asax.cs
file:
ContainerBuilder builder = new ContainerBuilder();
builder.Register(c => c.Resolve<HttpContextBase>().Request)
.As<HttpRequestBase>()
.InstancePerHttpRequest();
builder.Register(c => c.Resolve<HttpContextBase>().Response)
.As<HttpResponseBase>()
.InstancePerHttpRequest();
builder.Register(c => c.Resolve<HttpContextBase>().Server)
.As<HttpServerUtilityBase>()
.InstancePerHttpRequest();
builder.Register(c => c.Resolve<HttpContextBase>().Session)
.As<HttpSessionStateBase>()
.InstancePerHttpRequest();
builder.RegisterControllers(Assembly.GetExecutingAssembly());
builder.RegisterType<WebWorkContext>().As<IWorkContext>().InstancePerHttpRequest();
在我的家庭控制器中,我有这个(仅用于测试目的):
private readonly HttpContextBase httpContext;
public HomeController(HttpContextBase httpContext)
{
this.httpContext = httpContext;
}
我在 ASP.NET MVC 3 项目中使用了完全相同的代码,并且运行良好。现在在这个项目中我遇到了错误。不知道为什么?我收到的错误是:
无法使用可用的服务和参数调用类型“MyProject.Web.Controllers.HomeController”上的“Autofac.Core.Activators.Reflection.DefaultConstructorFinder”找到的任何构造函数:无法解析参数“System.Web.HttpContextBase httpContext”构造函数“Void .ctor(System.Web.HttpContextBase)”。在 Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext 上下文,IEnumerable1 parameters) at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable
1 个参数)位于 Autofac.Core.Resolving.InstanceLookup.Execute() 处 Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration 注册, IEnumerable1 parameters) at Autofac.Core.Resolving.InstanceLookup.ResolveComponent(IComponentRegistration registration, IEnumerable
1 个参数)位于 Autofac.Core.Registration.ExternalRegistrySource.
我不太确定为什么这行不通?我需要在 ASP.NET 4 中做不同的事情吗?
我有一个单独的项目,我也想在其中注入HttpContextBase
我遇到了同样的错误。