简体   繁体   中英

NHibernate Abstract Repository ISession Property in Concrete Class

I am not sure how to ask my question, so I will write a few lines of code...

I have an abstract base class AbstractRepository like this:

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

A concrete class that implements the abstract 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 suggests the following change for the line:

public ISession Session => base.Session;

TO

public new ISession Session => base.Session;

ReSharper 提示

Which one would should I use and why?

Can someone perhaps explain the reasoning for one over the other? Not sure if this is a lack of understanding of

  1. OOP,
  2. NHibernate plumbing
  3. Or both?

What is the reasoning for creating a 'new' ISession?

You cannot override a method unless it is abstract or virtual , so by doing this:

public ISession Session => base.Session;

You are hiding the base implementation rather than overriding it.

This causes the property's get implementation to be selected based on the reference rather than the instance.

In your specific example this makes little difference, however, here is an example where it would:

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

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

This happens because thisAsAbstract.Session uses the base implementation of Session as it has only been hidden.

The suggestion by ReSharper (to use the new keyword) is simply to make explicit that method hiding was intended rather than accidental, as in your case it seems to be (because you are changing the access modifier).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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