1
votes

In my setup class I have the following code (using Autofac and the MVC Web API Template in Visual Studio)

builder.RegisterType<CRMUserStore<IdentityUser>>().As<IUserLoginStore<IdentityUser>>()
    .InstancePerRequest();

Then in the Startup.Auth class I have the following

UserManagerFactory = () => new UserManager<IdentityUser>(
    DependencyResolver.Current.GetService<IUserLoginStore<IdentityUser>>());

This returns null. Then when I try instead of the above

UserManagerFactory = () => new UserManager<IdentityUser>(
    _container.Resolve<IUserLoginStore<IdentityUser>>()); //_container is IContainer

I get an error saying

An exception of type 'Autofac.Core.DependencyResolutionException' occurred in Autofac.dll but was not handled in user code

Additional information: No scope with a Tag matching 'AutofacWebRequest' is visible from the scope in which the instance was requested. This generally indicates that a component registered as per-HTTP request is being requested by a SingleInstance() component (or a similar scenario.) Under the web integration always request dependencies from the DependencyResolver.Current or ILifetimeScopeProvider.RequestLifetime, never from the container itself.

How do I fix this?

1

1 Answers

0
votes

Your IUserLoginStore service is being registered as InstancePerRequest which means it can only be resolved from within the context of a request. I.e. a lifetime scope tagged as 'AutofacWebRequest'.

AutoFac automatically creates a new lifetime scope tagged as 'AutofacWebRequest' for each request, and hence services resolved within the request can access this tagged scope. I would imagine that the Startup.Auth class is running at the scope of the MVC application and outside of any specific request. Therefore it doesn't have access to the tagged scope and hence the exception No scope with a Tag matching 'AutofacWebRequest'.

If this is the case then changing the IUserLoginStore registration to InstancePerLifetimeScope will allow it to resolve correctly within the Startup.Auth class.

However, this would also change the behaviour when resolving within a request to always getting the application scoped service as well. Without seeing more of your code I can't tell if this would be an issue.

Here's a related question with a nice writeup: Autofac - InstancePerHttpRequest vs InstancePerLifetimeScope

Note - Ensure you have configured Asp.Net MVC to use AutoFac for dependency resolution as described in the AutoFac documentation ( https://code.google.com/p/autofac/wiki/MvcIntegration ).

protected void Application_Start() { var builder = new ContainerBuilder(); builder.RegisterControllers(typeof(MvcApplication).Assembly); var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

// Other MVC setup...