0
votes

The Autofac has been configured in the Web Form application as following.

var builder = new ContainerBuilder();
BootStrapper.InitializeBizTypes(builder);
builder.RegisterType<Component>().**InstancePerRequest()**;
_containerProvider = new ContainerProvider(builder.Build());

In a page there's a GridView binding with ObjectDataSource, for ObjectDataSource, the SelectMethod is a method in a static class.

My codes in static class:

private static IComponentContext GetContainer()
    {
        var cpa = (IContainerProviderAccessor)HttpContext.Current.ApplicationInstance;
        return cpa.ContainerProvider.ApplicationContainer;
    }

    public static IList<RoleDto> GetRoles()
    {
        ***var biz = GetContainer().Resolve<IRoleBiz>();***
        return biz.GetRoles();
    }

I got below error when resolve the interface.

No scope with a tag matching 'AutofacWebRequest' is visible from the scope in which the instance was requested.

If you see this during execution of a web application, it 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 dependency resolver or the request lifetime scope, never from the container itself.

So my question is that how to resolve the registered types in a static class within asp.net web form application when the lifetime scope is "InstancePerRequest"?

1

1 Answers

0
votes

In order to resolve something from the request scope, you should use the RequestLifetime property of the IContainerProviderAccessor instead of the ApplicatonContainer

public static IList<RoleDto> GetRoles()
{
    var cpa = ((IContainerProviderAccessor)HttpContext.Current.ApplicationInstance);
    var scope = cpa.RequestLifetime; 

    var biz = scope.Resolve<IRoleBiz>();
    return biz.GetRoles();
}