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.
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) { ... }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With