Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing HttpContext and User Identity from data layer

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

Accessing HttpContext.User.Identity from within my Repository/Data layer is probably not a good idea.. or is it ? What's the best way to grab my user ( current identity ) information to record who the records were added or changed by ? Re-factoring the entire application to include user information in repository calls would be silly. I'm sure there is a better, more generic way.

like image 865
InspiredBy Avatar asked Apr 17 '15 20:04

InspiredBy


1 Answers

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) { ... }
}
like image 103
Marcelo De Zen Avatar answered Sep 21 '22 07:09

Marcelo De Zen