API中使用AutoFac在运行时解析服务

API中使用AutoFac在运行时解析服务

本文介绍了如何在Web API中使用AutoFac在运行时解析服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an API (eg: ItemController.cs) which would obtain the Authorization Token from the Request Header at run time. With the Token, then only I pass into my Service Class (eg: ServiceItem.cs).

这就是我的做法.

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

  1. At the Startup.cs, I register my ServiceItem

var builder = new ContainerBuilder();
builder.RegisterType<ServiceItem>();
container = builder.Build(); //Note that, my container is a static variable

  • 在我的API中,我通过以下方式解决了该问题:

  • In my API, I resolve it in this way:

    [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.其次,如果我再公开一些功能,这些代码看起来是重复的.

    Is this how the Autofac normally work in web API? First, i am using a global static IContainer. Second, the codes look repetitive if i expose a few more functions.

    我当时正在考虑在API的构造函数中解析ServiceItem.但是授权令牌尚不可用.

    I was thinking to resolve the ServiceItem in the constructor of the API. But the authorization token is not available yet.

    任何建议都值得赞赏.

    PS:

    这是我的ServiceItem,它在构造函数中具有参数令牌"

    Here's my ServiceItem which, in the constructor, has a param 'token'

         public class ServiceItem
         {
              public string token;
              public ServiceItem(string token)
              {
                  this.token = token;
              }
    
              public void doSomething()
              {
                  //based on token, do processing
              }
          }
    

    推荐答案

    在启动类中引用静态容器是一个坏主意.这样,您将在控制器和启动之间引入紧密耦合.您的控制器依赖性应通过构造函数参数来满足.进入 http://docs.autofac.org/en/v4. 0.0/integration/aspnetcore.html

    It is a bad idea to refer to a static container within your startup class. That way, you introduce tight coupling between the controller and the startup. Your controller dependencies should be satisfied by constructor parameters. Take at http://docs.autofac.org/en/v4.0.0/integration/aspnetcore.html

    Startup.ConfigureServices方法可以选择返回一个IServiceProvider实例,该实例使您可以将Autofac插入ASP.NET Core依赖注入框架:

    The Startup.ConfigureServices method can optionally return a IServiceProvider instance, which allows you to plug-in Autofac into the ASP.NET Core Dependency Injection framework:

    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自动解析:

    After initializing your container, constructor parameters will be automatically resolved by Autofac:

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

    这篇关于如何在Web API中使用AutoFac在运行时解析服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    07-22 11:13