代码之家  ›  专栏  ›  技术社区  ›  zeroflaw

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

  •  1
  • zeroflaw  · 技术社区  · 8 年前

    我有一个API( eg: ItemController.cs )它将在运行时从请求头获取授权令牌。有了令牌,只有我才能进入我的服务类( eg: ServiceItem.cs )。

    我是这样做的。

    1. 在启动时。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在web API中的正常工作方式吗?首先,我使用全局静态 IContainer 。其次,如果我公开更多的函数,代码看起来是重复的。

    我在考虑解决 ServiceItem 在API的构造函数中。但授权令牌尚不可用。

    欢迎提出任何建议。

    P、 S.:

    这是我的 服务项目 在构造函数中,具有参数“token”

         public class ServiceItem
         {
              public string token;
              public ServiceItem(string token)
              {
                  this.token = token;
              }
    
              public void doSomething()
              {
                  //based on token, do processing
              }
          }
    
    1 回复  |  直到 8 年前
        1
  •  3
  •   mbnx    8 年前

    在startup类中引用静态容器是个坏主意。这样,就在控制器和启动之间引入了紧密耦合。构造函数参数应该满足控制器依赖关系。接受 http://docs.autofac.org/en/v4.0.0/integration/aspnetcore.html

    这个 Startup.ConfigureServices 方法可以选择性地返回 IServiceProvider 实例,它允许您将Autofac插件到ASP。NET Core依赖项注入框架:

    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; 
        }
    
        ....
    }