• autofac 在webapi中拿到当前request的scope


    https://stackoverflow.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

    在和Owin集成的web api中GlobalConfiguration.Configuration是无法使用的。需要使用其他方法

    https://www.cnblogs.com/chucklu/p/10420034.html

    https://stackoverflow.com/questions/28725753/owin-service-resolution-using-autofac

    If you are in a DelegatingHandler or an ApiController you will have a reference to the current HttpRequestMessage. Use message.GetDependencyScope() to get the current request-level dependency scope to resolve services.

    public HttpResponseMessage SomeControllerAction()
    {
      var service = this.Request.GetDependencyScope().GetService(typeof(Service));
    }
    
     protected override async void Initialize(HttpControllerContext controllerContext)
            {
                string requestBody = await controllerContext.Request.Content.ReadAsStringAsync();
                SecurityCheckResult securityCheckResult = requestAnalyzer.SecurityCheck(requestBody);
                if (securityCheckResult.Success)
                {
                    var dependencyScope = controllerContext.Request.GetDependencyScope();
                    var lifetimeScope = dependencyScope.GetRequestLifetimeScope();
                    var parameter = new NamedParameter("OpCo", securityCheckResult.OpCo);
                    Program = lifetimeScope.Resolve<IProgramContract>(parameter);
                    Service = lifetimeScope.Resolve<IDynamicProfileService>(parameter);
                }
    
                LogUtil.CreateLog(LogLevel.Message, $"BaseApiController.Initialize");
                base.Initialize(controllerContext);
            }

    源码

    https://github.com/autofac/Autofac.WebApi/blob/develop/src/Autofac.Integration.WebApi/DependencyResolverExtensions.cs

    using System.Web.Http.Dependencies;
    
    namespace Autofac.Integration.WebApi
    {
        /// <summary>
        /// Extension methods to the <see cref="IDependencyResolver"/> interface.
        /// </summary>
        public static class DependencyResolverExtensions
        {
            /// <summary>
            /// Gets the root lifetime scope from the Autofac dependency resolver.
            /// </summary>
            /// <param name="dependencyResolver">
            /// The dependency resolver from which the root lifetime scope should be retrieved.
            /// </param>
            public static ILifetimeScope GetRootLifetimeScope(this IDependencyResolver dependencyResolver)
            {
                var resolver = dependencyResolver as AutofacWebApiDependencyResolver;
                return (resolver == null) ? null : resolver.Container;
            }
    
            /// <summary>
            /// Gets the request lifetime scope from the Autofac dependency scope.
            /// </summary>
            /// <param name="dependencyScope">
            /// The dependency scope from which the request lifetime scope should be retrieved.
            /// </param>
            public static ILifetimeScope GetRequestLifetimeScope(this IDependencyScope dependencyScope)
            {
                var scope = dependencyScope as AutofacWebApiDependencyScope;
                return (scope == null) ? null : scope.LifetimeScope;
            }
        }
    }

    而Microsoft.AspNet.WebApi.Core.5.2.7中,有一个扩展HttpRequestMessage的静态类public static class HttpRequestMessageExtensions

    public static IDependencyScope GetDependencyScope(this HttpRequestMessage request);

    所以我们可以通过request去拿到IDependencyScope 。

    然后autofac扩展了IDependencyScope ,增加了1个GetRequestLifetimeScope的方法,拿到这个scope就可以进行resolve了。

  • 相关阅读:
    c++ 设计模式3 (重构技法 Template Method)
    C++ 设计模式2 (面向对象设计原则)
    c++ 设计模式1
    算法总结—二分搜索与旋转排序数组
    c++ 构造函数,拷贝构造函数,析构函数与赋值操作符
    题解 P2330 【[SCOI2005]繁忙的都市】
    题解 CF896C 【Willem, Chtholly and Seniorious】
    题解 P3369 【【模板】普通平衡树】
    题解 CF383C 【Propagating tree】
    题解 P1179 【数字统计】
  • 原文地址:https://www.cnblogs.com/chucklu/p/10429218.html
Copyright © 2020-2023  润新知