How can I add additional features to my User class

Viewed 66

I am working on an Online shopping project. I used JWT for authentication. My User.cs class is:

namespace Core.Entities.Concrete
{
    public class User:  IEntity 
    {
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public byte[] PasswordHash { get; set; }
        public byte[] PasswordSalt { get; set; }
        public bool Status { get; set; }
        /// <summary>
        /// A person can have multiple Orders
        /// </summary>
        public virtual ICollection<Order> Orders { get; set; } //*Could not be found Error*
        public User() => Orders = new List<Order>(); //*Could not be found Error*
    }
}

I want to add Orders feature to my User class, a customer can order products. But Usre.cs class is in Core layer which hasn't dependency to Entities layer(Order class inside) How can I solve this issue?

I shouldn't give Core layer reference to Entities Layer.

Laysers

1 Answers

Consider separating Order and User by using dependency injection.

For example we could create an interface called IOrder that defines the properties and methods that Order.cs has, and the required methods and properties User should be able to access.

Then we can inject that dependency into the UI layer.

services.AddTransient<IOrder,Entities.Order>();

Then we can inject that dependency in the user class through it's constructor such as:

public class User : IEntity
{
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public byte[] PasswordHash { get; set; }
    public byte[] PasswordSalt { get; set; }
    public bool Status { get; set; }
    
    /// <summary>
    /// A person can have multiple Orders
    /// </summary>
    public virtual ICollection<IOrder> Orders { get; set; }

    public User(List<IOrder> Orders) // <-- automatically injected with most DI setups
    {
        this.Orders = Orders;
    }
}

Edit:
For more resources on what dependency injection is, and how to use it check out these resources. This one covers dependency injection ins ASP.NET in general, and this one covers dependency injection specifically in Entity-Framework, the thing you tagged as using using.

Related