Accessing HttpContext and User Identity from data layer

前端 未结 6 1972
Happy的楠姐
Happy的楠姐 2021-02-15 11:08

I need to implement AddedBy/ChangedBy type fields on my Base Entity that all other entities inherit from ( Fluent Nhibernate ).

Accessing HttpContext.User.Identity

6条回答
  •  青春惊慌失措
    2021-02-15 11:41

    Access the HttpContext from the Data Layer makes the life harder, specially if you use Unit Tests. The solution is to create a service to provide application wide user information, something like:

    public interface ICurrentUserService {
       string UserName {get;}
       string UserId {get;}
       string HostIP {get;}
       // etc.
    }
    

    Then you can implement the concrete service and inject it using your preferred IoC container.

    public class CurrentWebUserService : ICurrentUserService {
        // implement interface members 
        public CurrentWebUserService(HttpContext context) { ... }
    
        public string UserName { get { ... } } 
        // etc.
    }
    
    // maybe you want a stub service to inject while unit testing.
    public class CurrentUserServiceStub : ICurrentUserService {
    
    }
    
    // data layer
    public class MyDaoService {
        public DaoService(ICurrentUserService currentUser) { ... }
    }
    

提交回复
热议问题