Resolution Problem with HttpRequestScoped in Autofac
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<IAccountServi开发者_Python百科ce>())).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?
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.
I got the same error. I solved it moving the registration instructions to the Application_BeginRequest section in global.asax.cs
builder.Register(c => new MyDataContext(connectionString)).As<IDatabase>().SingleInstance();
builder.Register(c => new UnitOfWork(c.Resolve<IDatabase>())).As<IUnitOfWork>().SingleInstance();
builder.Register(c => new AccountService(c.Resolve<IDatabase>())).As<IAccountService>();
builder.Register(c => new AccountController(c.Resolve<IAccountService>())));
Then I have the disposal of the container:
protected void Application_EndRequest()
{
ContainerProvider.EndRequestLifetime();
}
精彩评论