Using virtual properties to support NHibernate proxies; ReSharper warns of virtual member call in constructor

StackOverflow https://stackoverflow.com/questions/22101636

  •  18-10-2022
  •  | 
  •  

Question

I'm trying to support NHibernate proxying of my entities by marking the entities' properties as virtual:

public class Video : IAbstractDomainEntity<string>
{
    public virtual string Id { get; set; }
    public virtual string Title { get; set; }
    public virtual int Duration { get; set; }
    public virtual string Author { get; set; }
    public virtual bool HighDefinition { get; set; }

    public Video()
    {
        Id = string.Empty;
        Title = string.Empty;
        Author = string.Empty;
    }
}

ReSharper states that this is bad practice due to the issue described here: Virtual member call in a constructor

I understand the problem and I also understand that I cannot mark my class as sealed because then NHibernate would not be able to generate a proxy from the entity.

Do I just live with the waning and make sure not to do anything weird with my setters?

Was it helpful?

Solution

The best-practice is to use properties with backing fields:

public class Video : IAbstractDomainEntity<string>
{
    private string _id;
    private string _title;
    private string _author;

    public virtual string Id
    {
        get { return _id; }
        set { _id = value; }
    }
    public virtual string Title
    {
        get { return _title; }
        set { _title = value; }
    }
    public virtual string Author
    {
        get { return _author; }
        set { _author = value; }
    }
    public virtual int Duration { get; set; }
    public virtual bool HighDefinition { get; set; }

    public Video()
    {
        _id = string.Empty;
        _title = string.Empty;
        _author = string.Empty;
    }
}

So you can avoid problems on child classes and you don't see any warning anymore

OTHER TIPS

I prefer the more concise, encapsulated variant:

public class Video : IAbstractDomainEntity<string>
{
    public virtual string Id { get; protected set; }
    public virtual string Title { get; protected set; }
    public virtual string Author { get; protected set; }
    public virtual int Duration { get; protected set; }
    public virtual bool HighDefinition { get; protected set; }

    public static Video Create()
    {
        return new Video 
        {
            Id = string.Empty,
            Title = string.Empty,
            Author = string.Empty
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top