我创建的AuditService
看起来像是:
public interface IAuditService
{
void Log(int userId, string obj, string action, string details);
}
在我的控制器中,我可以像这样调用服务:
public class AccountController : BaseController
{
private readonly IAuditService _auditService;
public AccountController(IUnitOfWork unitOfWork, IAuditService auditService) : base(unitOfWork)
{
...
_auditService = auditService;
}
[HttpPost]
public ActionResult UserProfile(ProfileViewModel vm)
{
...
_auditService.Log(CurrentUser.UserId,"Account", "Edit", "details");
}
}
这很好用,但是我需要在用户登录时进行记录。在Global.asax文件中,我有一个Session_start()方法来获取登录用户。我也需要能够从这里拨打AuditService
。
protected void Session_Start(object sender, EventArgs e)
{
if (Request.IsAuthenticated)
{
var sid = System.Web.HttpContext.Current.Request.LogonUserIdentity.User.ToString();
using (var context = new SqlContext())
{
SystemUser user = context.SystemUsers.Where(u => u.UserSid == sid).FirstOrDefault();
if (user != null)
{
user.LastLogin = DateTime.Now;
context.SaveChanges();
}
}
}
}
有关我应该尝试的建议吗?我尝试过类似下面的几行,但我收到了invalid argument
错误。
AuditService audit = new AuditService(DependencyResolver.Current.GetService<IAuditService>().Log);
audit.Log(user.UserId, "Account", "Login", "Successfull login");
答案 0 :(得分:2)
由于您使用Autofac作为依赖项解析程序,因此您可以使用以下命令获取对IAuditService
实现的引用:
IAuditService audit = DependencyResolver.Current.GetService<IAuditService>();
然后调用它的方法:
audit.Log(user.UserId, "Account", "Login", "Successfull login");