繁体   English   中英

NHibernate 抽象存储库 ISession 属性在具体 Class

[英]NHibernate Abstract Repository ISession Property in Concrete Class

我不知道如何问我的问题,所以我会写几行代码......

我有一个像这样的抽象基础 class AbstractRepository

 public abstract class AbstractRepository : IGenericRepository
    {       
        protected ISession Session
        {
            get
            {
                return Startup.SessionFactory.GetCurrentSession();
            }            
        }
          
        //More code left out for clarity
}

实现抽象 class 的具体 class,AbstractRepository:

 public class AccommodationRepository : AbstractRepository
    {                                                
        // Allow the Session property to be returned from the base class.
        public ISession Session => base.Session;
        
        // Which I understand to be the same as the line below:
        // public ISession session { get { return base.Session; } }

        public async Task<EPICCard> GetByCardNumber(long epicCardId)
        {
            var session = Session;
            
            CancellationTokenSource token = new CancellationTokenSource();
           
            //Do stuff - not important for now.

            return theQueryTask.Result;
        }
    }

Re-Sharper 建议对该行进行以下更改:

公共 ISession Session => base.Session;

公共新ISession Session => base.Session;

ReSharper 提示

我应该使用哪一个,为什么?

有人可以解释其中一个的原因吗? 不知道是不是理解不够

  1. OOP,
  2. NHibernate 水暖
  3. 或两者?

创建“新”ISession 的原因是什么?

你不能覆盖一个方法,除非它是abstractvirtual ,所以这样做:

public ISession Session => base.Session;

您正在隐藏基本实现而不是覆盖它。

这会导致基于引用而不是实例来选择属性的get实现。

在您的具体示例中,这几乎没有什么区别,但是,这是一个示例:

public class AccommodationRepository : AbstractRepository
{
    public ISession Session => new SomeOtherSession();

    void SomeMethod()
    {
        AbstractRepository thisAsAbstract = this;
        object.ReferenceEquals(this.Session, thisAsAbstract.Session); // false
    }
}

这是因为thisAsAbstract.Session使用了Session的基本实现,因为它只是被隐藏了。

ReSharper 的建议(使用new关键字)只是为了明确表明方法隐藏是有意的而不是偶然的,就像您的情况一样(因为您正在更改访问修饰符)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM