autofac 在webapi中拿到当前request的scope

https://*.com/questions/31321386/autofac-web-api-get-current-scope

 

Unless you are using OWIN in your API, you should have your Autofac configuration setup in your WebAPI like this, which is the standard way to configure Autofac for WebApi.

Include nuget pacakge Autofac.Integration.WebApi

var builder = new ContainerBuilder();
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterType<MyType>();

var container = builder.Build();
var resolver = new AutofacWebApiDependencyResolver(container);
GlobalConfiguration.Configuration.DependencyResolver = resolver;

Should you need to request the LifetimeScope like in your example, you can then request this from GlobalConfiguration.

var scope = GlobalConfiguration.Configuration.DependencyResolver.GetRequestLifetimeScope();
MyService service = scope.Resolve<MyService>();

Autofac WebApi configuration reference

 

上一篇:Ioc容器Autofac系列(1)-- 初窥


下一篇:c# – 如何使用autofac注册开放泛型类型,封闭泛型类型和装饰?