Autofac 每个请求 Web Api 2 + Owin

Autofac PerRequest WebApi 2 + Owin

正在尝试使用我的 WebApi 实现 autofac ...但是我的对象的生命周期存在一些问题...

我的启动 webapi class:

var builder = new ContainerBuilder();
builder.RegisterApiControllers(Assembly.GetExecutingAssembly()).InstancePerRequest();

    container.RegisterType<MyConcreteClass>().As<IMyInterface>().InstancePerRequest();

    var container = builder.Build();

    app.UseAutofacMiddleware(container);
    app.UseAutofacWebApi(config);


    var csl = new AutofacServiceLocator(container);
    ServiceLocator.SetLocatorProvider(() => csl);


    config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

但是不行

无法解析类型 'IMyInterface',因为无法找到它所属的生命周期范围。此注册公开了以下服务: - IMyInterface

详细信息 ---> 从请求实例的范围中看不到标签匹配 'AutofacWebRequest' 的范围。

如果您在 Web 应用程序执行期间看到此信息,通常表示 SingleInstance() 组件(或类似情况)正在请求注册为每个 HTTP 请求的组件。在 Web 集成下,总是从依赖解析器或请求生命周期范围请求依赖,从不从容器本身请求依赖。 (有关详细信息,请参阅内部异常。)

删除这部分 .InstancePerRequest(); ,然后工作,但对象没有处理。

我做错了什么?

谢谢!

我强烈怀疑问题出在以下代码上:

var csl = new AutofacServiceLocator(container);
ServiceLocator.SetLocatorProvider(() => csl);

错误消息表明您必须使用依赖项解析器解析依赖项,但这是绕过它并使用容器本身。

On a side note, using a service locator is anti-pattern. You should be injecting dependencies into your controllers and other MVC extension points rather than using this approach.