【问题标题】:Using a class property while calling the base constructor and in helper methods在调用基本构造函数和辅助方法时使用类属性
【发布时间】:2018-03-10 16:54:01
【问题描述】:

我有这个sn-p的代码--

public class UserManager : UserManager<ApplicationUser>
{
    private ApplicationDbContext _dbAccess;
    public UserManager() : 
         base(new UserStore<ApplicationUser>(new ApplicationDbContext()))
    {
        this.UserValidator = new CustomUserValidator<ApplicationUser>(this);
        var provider = new MachineKeyProtectionProvider();
        this.UserTokenProvider = 
                 new DataProtectorTokenProvider<ApplicationUser>(
                            provider.Create("SomeCoolAuthentication"));

       //DO I REALLY NEED TO DO THIS AGAIN?
       this._dbAccess = new ApplicationDBContext(); 
    }

    public bool myOwnHelperMethod(){
        //is there a way to use the ApplicationDbContext instance that 
        //was initialized in the base constructor here? 
        //Or do i have to create a new instance?
    }
}

有没有更好的方法来编写它,以便我可以实例化 ApplicationDBContext,使用它来调用基本构造函数,然后稍后在一些辅助方法中使用相同的实例?还是我必须在构造函数中创建另一个实例以用于辅助方法。

【问题讨论】:

  • @S.Akbari 请解释您提出该建议的原因。这看起来是一个很好的 Stack Overflow 问题。
  • @200_success 有没有更好的写法?
  • @S.Akbari 请查看Code Review help center。注意到什么了吗?示例代码不可接受。

标签: c# class-constructors


【解决方案1】:

将此属性添加到您的 UserManager 类中:

 private ApplicationDbContext Context
 {
      get { return ((UserStore<ApplicationUser>)this.Store).Context as ApplicationDbContext; }
 }

UserManager 类公开了一个 Store 属性。由于您知道内部使用的对象类型,因此您可以直接转换它们并在代码中使用 Context 属性。

【讨论】:

  • Store 被标记为internal。可以这样引用吗?
  • @Amy: UserManager 继承自 UserManager&lt;ApplicationUser&gt; 所以内部成员应该可用。
  • @Juan 内部成员仅限于同一个程序集。它与继承无关。我无法在此处编译您的代码。
  • 应该是protected 让它工作,而不是internal。如果仅是 internal,则在定义程序集之外将无法访问它。
  • 谢谢@Juan 和@KirkLarkin!我采用了依赖注入方法!完美运行。
【解决方案2】:

你有几个选择。

首先是使用依赖注入。使用这种方法,您可以将 ApplicationDbContext 的创建删除到 UserManager 之外,并通过构造函数将其传入。例如:

public class UserManager : UserManager<ApplicationUser>
{
    private ApplicationDbContext _dbAccess;

    public UserManager(ApplicationDbContext dbAccess) : 
         base(new UserStore<ApplicationUser>(dbAccess))
    {
        ...

        this._dbAccess = dbAccess; 
    }

    ...
}

我刚要建议的第二个选项已由@Juan 在他的回答中提供,所以我不会在这里重复。

【讨论】:

    猜你喜欢
    • 2015-01-28
    • 1970-01-01
    • 1970-01-01
    • 2011-06-28
    • 2019-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多