user5550554
user5550554

Reputation:

Unity Of Work + Rich domain

I'm trying to implement a rich model with Unit of Work.

public class User : BusinessBase, IUser
    {
        public int UserID { get; }
        public string Name { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
        public string Token { get; set; }
        public DateTime SigninDate { get; set; }
        public DateTime LastLogin { get; set; }


        public User(IUnityOfWork uow) : base(uow)
        {

        }

        public void Create(User user)
        {
            Name = user.Name;
            LastName = user.LastName;
            Email = user.Email;
            Password = user.Password; //TODO HASH
            Token = GetToken();
            SigninDate = DateTime.Now;
            LastLogin = DateTime.Now;
            Uow.User.Add(this);
        }

    }

The build runs ok, but in this class the unit of work is null.

I do have a interface with to this class.

interface IUser: ICommitable
    {
        void Create(User user);
        void Delete();
        void EditName(string name);
        void EditLastName(string lastName);
        void EditEmail(string email);
        void EditPassword(string password);
        void GenerateToken();
        string GetToken();
        void UpdateLoginDate();
    }

and at UnityConfig.cs, I register the type

container.RegisterType<IUser, User>();

Why isn't Unit Of Work not being initialized, and how can I solve this?

Upvotes: 0

Views: 93

Answers (1)

user5550554
user5550554

Reputation:

So I found the mistake I was not using the interface IUser to call the model method.

 public class UsersController : ApiControllerBase
    {


        [HttpPost]
        [AllowAnonymous]
        public DtoResultBase CreateUser(User user)
        {
            return Resolve(() =>
            {
                user.Create(user);
                user.Commit();
                return new DtoResultBase();
            });
        }

Now with the interface implemented in the controller:

 public class UsersController : ApiControllerBase
    {

        private IUser UserBusiness;

        public UsersController(IUser userBusiness)
        {
            UserBusiness = userBusiness;
        }


        [HttpPost]
        [AllowAnonymous]
        public DtoResultBase CreateUser(User user)
        {
            return Resolve(() =>
            {
                UserBusiness.Create(user);
                UserBusiness.Commit();
                return new DtoResultBase();
            });
        }

Upvotes: 0

Related Questions