Autofac 中 HttpRequestScoped 的解决问题
我正在尝试解决应用程序中的 AccountController 问题,但似乎我遇到了生命周期范围问题。
builder.Register(c => new MyDataContext(connectionString)).As<IDatabase>().HttpRequestScoped();
builder.Register(c => new UnitOfWork(c.Resolve<IDatabase>())).As<IUnitOfWork>().HttpRequestScoped();
builder.Register(c => new AccountService(c.Resolve<IDatabase>())).As<IAccountService>().InstancePerLifetimeScope();
builder.Register(c => new AccountController(c.Resolve<IAccountService>())).InstancePerDependency();
我需要将 MyDataContext 和 UnitOfWork 的范围限定在 HttpRequestLevel 内。 当我尝试解析 AccountController 时,出现以下错误:
没有范围匹配表达式 'value(Autofac.Builder.RegistrationBuilder`3+<>c__DisplayClass0[...]).lifetimeScopeTag.Equals(scope.Tag) ' 从请求实例的范围中可见。
我的依赖生命周期是否设置不正确?
I'm trying to resolve the AccountController in my application, but it seems that I have a lifetime scoping issue.
builder.Register(c => new MyDataContext(connectionString)).As<IDatabase>().HttpRequestScoped();
builder.Register(c => new UnitOfWork(c.Resolve<IDatabase>())).As<IUnitOfWork>().HttpRequestScoped();
builder.Register(c => new AccountService(c.Resolve<IDatabase>())).As<IAccountService>().InstancePerLifetimeScope();
builder.Register(c => new AccountController(c.Resolve<IAccountService>())).InstancePerDependency();
I need MyDataContext and UnitOfWork to be scoped at the HttpRequestLevel.
When I try to resolve the AccountController, I get the following error:
No scope matching the expression 'value(Autofac.Builder.RegistrationBuilder`3+<>c__DisplayClass0[...]).lifetimeScopeTag.Equals(scope.Tag)' is visible from the scope in which the instance was requested.
Do I have my dependency lifetimes set up incorrectly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的设置看起来不错 - 我猜问题是您正在尝试从 IContainerProvider.ApplicationContainer 解析 AccountController (手动?)。
您需要从 IContainerProvider.RequestLifetime(1.x 中的 RequestContainer)解析 Web 应用程序中的依赖项。
您是否尝试过 Autofac ASP.NET MVC 集成?它会为你处理这件事。
Your setup looks fine - I'd guess that the problem is that you're trying to resolve AccountController (manually?) from IContainerProvider.ApplicationContainer.
You need to resolve dependencies in a web app from IContainerProvider.RequestLifetime (RequestContainer in 1.x).
Have you tried the Autofac ASP.NET MVC integration? It would take care of this for you.
我遇到了同样的错误。我解决了这个问题,将注册指令移动到 global.asax.cs 中的 Application_BeginRequest 部分
然后我可以处理容器:
I got the same error. I solved it moving the registration instructions to the Application_BeginRequest section in global.asax.cs
Then I have the disposal of the container: