从Session_Start呼叫服务

时间:2015-05-20 17:16:07

标签: asp.net-mvc-4 autofac unit-of-work

我创建的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");

1 个答案:

答案 0 :(得分:2)

由于您使用Autofac作为依赖项解析程序,因此您可以使用以下命令获取对IAuditService实现的引用:

IAuditService audit = DependencyResolver.Current.GetService<IAuditService>();

然后调用它的方法:

audit.Log(user.UserId, "Account", "Login", "Successfull login");

请参阅DependencyResolver