【问题标题】:WebAPI DI Framework that understands HttpContext.User理解 HttpContext.User 的 WebAPI DI 框架
【发布时间】:2016-05-25 05:33:26
【问题描述】:

我正在寻找可以满足这种场景的 DI 框架:

每个控制器都有这样的构造函数

public ThisController( ThatRepository repo)

每个存储库都有一个这样的控制器:

public ThatRepository (DataSource ds)

有一个主数据源,但从未传递到存储库。相反,它需要:

MasterDataSource.WithUser ( httpContext?.User?.Identity?.Name )

是否有任何适用于 WebAPI 的 DI 框架可以开箱即用地支持这一点?

【问题讨论】:

标签: c# asp.net-web-api dependency-injection httpcontext


【解决方案1】:

我相信您几乎可以将每个 DI 容器用于此目的,方法是在容器内注册当前HttpContext(甚至是当前用户Identity),然后将其注入以构建您的DataSource 实例。

这是一个在 SimpleInjector 中使用HttpContext 的简单解决方案(您可以轻松地将代码移植到您喜欢的任何 DI 框架):

container.Register<HttpContextBase>(() =>
    new HttpContextWrapper(HttpContext.Current), 
    Lifestyle.Scoped);

container.Register<DataSource>(() =>
    {
        var httpContext = container.GetInstance<HttpContextBase>();
        return MasterDataSource.WithUser(httpContext?.User?.Identity?.Name);
    }, 
    Lifestyle.Scoped);

【讨论】:

    【解决方案2】:

    在您控制的接口后面抽象HttpContext,并让您选择的 DI 容器在需要时解决该问题。

    public interface ICurrentUser {
        string Name{get;}
    }
    

    该接口的具体实现可能看起来像...

    public class UserProvider : ICurrentUser {
        HttoContextBase httpContext;
        UserProvider(){
            httpContext = HttpContext.Current;
        }
        public string Name { 
            get{ return httpContext?.User?.Identity?.Name ?? string.Empty; } 
        }
    }
    

    您在 DI 容器中注册您的接口/合同,并在需要时为您的 DataSource 解决它。

    public void SomeSetupMethod(ICurrentUser user) {
        MasterDataSource.WithUser(user?.Name);
    }
    

    【讨论】:

      猜你喜欢
      • 2010-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-05
      • 2013-09-02
      • 1970-01-01
      相关资源
      最近更新 更多