我正在使用ASP.NET MVC 4
和Autofac
。我有一个WebWorkContext
类,我在我的解决方案的各个地方注入了一个类,以获取当前员工的详细信息。
这是我的 global.asax 文件中的 Autofac 注册:
protected void Application_Start()
{
// Autofac
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterModule(new AutofacWebTypesModule());
builder.RegisterControllers(Assembly.GetExecutingAssembly());
builder.RegisterType<WebWorkContext>().As<IWorkContext>().InstancePerHttpRequest();
IContainer container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
我的 WebWorkContext 类:
public class WebWorkContext : IWorkContext
{
private readonly IEmployeeService employeeService;
private readonly HttpContextBase httpContext;
public WebWorkContext(IEmployeeService employeeService, HttpContextBase httpContext)
{
this.employeeService = employeeService;
this.httpContext = httpContext;
}
public Employee CurrentEmployee
{
get
{
return GetCurrentEmployee();
}
}
protected Employee GetCurrentEmployee()
{
string identityName = this.httpContext.User.Identity.Name.ToLower();
// Do what I need to do to get employee details from
// the database with identityName
}
}
我会在以下位置设置一个断点:
string identityName = this.httpContext.User.Identity.Name.ToLower();
identityName
总是空的。不知道为什么?我错过了什么吗?
我如何使用 WebWorkContext 类:
public class CommonController : Controller
{
private readonly IWorkContext workContext;
public CommonController(IWorkContext workContext)
{
this.workContext = workContext;
}
public ActionResult EmployeeInfo()
{
Employee employee = workContext.CurrentEmployee;
EmployeeInfoViewModel viewModel = Mapper.Map<EmployeeInfoViewModel>(employee);
return PartialView(viewModel);
}
}
我正在使用Visual Studio 2012
.