【问题标题】:ASP.NET Core userManager and context in separated controller分离控制器中的 ASP.NET Core userManager 和上下文
【发布时间】:2019-04-05 12:54:45
【问题描述】:

我想为 userManager 和 dbcontext 创建单独的控制器。 我想从这个控制器继承。 我不想使用构造函数注入依赖项,因为这样我就必须将构造函数也添加到另一个控制器。 还有其他方法吗?

private UserManager<ApplicationUser> _userManager;
private ApplicationDbContext _context;

ApplicationDbContext Context
{
    get
    {
        if(this._context == null)
        {
            // GET CONTEXT <= HOW TO DO THIS?
        }
        return this._context;
    }
}

UserManager<ApplicationUser> UserManager
{
    get
    {
        if(this._userManager == null)
        {
            // GET USER MANAGER <= HOW TO DO THIS?
        }
        return this._userManager;
    }
}

【问题讨论】:

    标签: c# asp.net-core


    【解决方案1】:

    如果您完全反对使用依赖注入,您可以使用服务定位器模式,但我建议您不要使用它,原因在 Service Locator is an Anti-Pattern 中详述。

    如果您仍然不想使用依赖注入,您可以使用HttpContext.RequestServices 访问IServiceProvider 实例并使用其GetRequiredService 方法来请求您所追求的类型,像这样:

    ApplicationDbContext Context
    {
        get
        {
            if (this._context == null)
            {
                this._context = HttpContext.RequestServices.GetRequiredService<ApplicationDbContext>();
            }
    
            return this._context;
        }
    }
    
    UserManager<ApplicationUser> UserManager
    {
        get
        {
            if (this._userManager == null)
            {
                this._userManager = HttpContext.RequestServices.GetRequiredService<UserManager<ApplicationUser>>();
            }
    
            return this._userManager;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-04
      • 2017-10-29
      • 2022-07-09
      • 2021-06-15
      • 2016-07-31
      • 1970-01-01
      • 2016-06-08
      相关资源
      最近更新 更多