如何在 Web API 中使用 AutoFac 在运行时解析服务?

How to use AutoFac in Web API to resolve a service at runtime?

我有一个 API (eg: ItemController.cs),它将在 运行 时从请求 Header 中获取授权令牌。使用令牌,然后只有我传递到我的服务 Class (eg: ServiceItem.cs).

我是这样做的。

  1. 在 Startup.cs,我注册了我的 ServiceItem

    var builder = new ContainerBuilder();
    builder.RegisterType<ServiceItem>();
    container = builder.Build(); //Note that, my container is a static variable
    
  2. 在我的API中,我是这样解决的:

    [Authorize]
    [Route("GetData")]
    [HttpGet]
    public IHttpActionResult GetData([FromUri] Filter filter)
    {
     using (var scope = Startup.container.BeginLifetimeScope())
     {
        var serviceItem = Startup.container.Resolve<ServiceItem>(
                new NamedParameter("token", Request.GetHeader("Authorization"))
            );
        return Ok(serviceItem.getItem(filter)); //filter is a param from webAPI
     }
    }
    

问题:

这就是 Autofac 在网络中正常工作的方式 API?首先,我使用的是全局静态 IContainer。其次,如果我再公开几个函数,代码看起来会重复。

我想在 API 的构造函数中解析 ServiceItem。但是授权令牌还不可用。

欢迎任何建议。

P.S.:

这是我的 ServiceItem,它在构造函数中有一个参数 'token'

     public class ServiceItem
     {
          public string token;
          public ServiceItem(string token)
          {
              this.token = token;
          }

          public void doSomething()
          {
              //based on token, do processing
          }
      }

在您的启动中引用静态容器是个坏主意class。这样,您就可以在控制器和启动之间引入紧密耦合。您的控制器依赖项应由构造函数参数满足。拍摄于 http://docs.autofac.org/en/v4.0.0/integration/aspnetcore.html

Startup.ConfigureServices 方法可以选择 return 一个 IServiceProvider 实例,它允许您 plug-in Autofac 进入 ASP.NET 核心依赖注入框架:

public IServiceProvider ConfigureServices(IServiceCollection services)
{
  services.AddMvc();

  var builder = new ContainerBuilder();

  builder.RegisterType<MyType>().As<IMyType>();
  builder.Populate(services);
  this.ApplicationContainer = builder.Build();

  return new AutofacServiceProvider(this.ApplicationContainer);
}

初始化容器后,Autofac 将自动解析构造函数参数:

public class MyController
{
    private readonly IMyType theType;
    public MyController(IMyType theType)
    {
        this.theType = theType; 
    }

    ....
}