Autofac 错误 - 从请求实例的范围中看不到标签匹配 'AutofacWebRequest' 的范围

Autofac error - No scope with a Tag matching 'AutofacWebRequest' is visible from the scope in which the instance was requested

在我的一个网络应用程序中,我有一个使用 Autofac 的网络服务,svc 文件如下:

<%@ ServiceHost Language="C#" Debug="true" 
Service="MyApp.WebServices.Contracts.Interfaces.IMyWebService, MyApp.WebServices.Contracts" 
Factory="Autofac.Integration.Wcf.AutofacServiceHostFactory, Autofac.Integration.Wcf" %>

我像这样为我的 Web 服务应用程序注册依赖项:

public class IocConfig
{        
    public static void RegisterDependencies()
    {
        var builder = new ContainerBuilder();            

        //web services
        builder.RegisterType<MyWebService>().As<IMyWebService>().InstancePerLifetimeScope();

        var container = builder.Build();

        AutofacHostFactory.Container = container;            
    }
}

我想从另一个 Web 应用程序连接到那些也使用 Autofac 的服务,因此我注册了如下依赖项:

public class IocConfig
{
    //Ioc dependencies for frontend application
    public static void RegisterDependencies()
    {
        var builder = new ContainerBuilder();

        builder.RegisterControllers(typeof(MvcApplication).Assembly);

        builder.RegisterModule<AutofacWebTypesModule>();

        builder
            .Register(c => new ChannelFactory<ISomeWebService>(
                new BasicHttpBinding(),
                new EndpointAddress("http://localhost/MyApp.WebServices/MyWebService.svc")))
            .InstancePerLifetimeScope();

        //register service proxies
        builder.Register(c => c.Resolve<ChannelFactory<IMyWebService>>().CreateChannel())
            .As<IMyWebService>()
            .UseWcfSafeRelease();

        var container = builder.Build();
        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
    }
}

在其中一个控制器中,我执行以下操作:

public SomeController(IMyWebService myServiceProxy) 
    {
        _myServiceProxy = myServiceProxy;

        var response =_myServiceProxy.CallSomeMethod(new Request()
        {
            EmailAddress = "test@test.com"
        });
    }

正在解析 IMyWebService 类型的 myServiceProxy,我看到它是一个透明代理,但是当我调用 "CallSomeMethod" 时出现错误:

从请求实例的范围中看不到具有匹配 'AutofacWebRequest' 的标记的范围。这通常表示注册为每个 HTTP 请求的组件正在被 SingleInstance() 组件(或类似场景)请求。在 Web 集成下,始终从 DependencyResolver.Current 或 ILifetimeScopeProvider.RequestLifetime 请求依赖项,从不来自容器本身。

我在这里做错了什么?谢谢!

Per the docs, WCF doesn't support per-request lifetime scope. 如果您的服务实现正在使用依赖项,则无法根据请求注册它们。

There is an FAQ telling you how to troubleshoot this and alternatives you can use.