我是 ServiceStack 新手,所以这可能是一个菜鸟问题:
我正在开发一个使用 ServiceStack 的 ASP.NET MVC4 应用程序,并试图弄清楚如何从 MVC4 使用的类(EF 上下文或 PetaPoco 数据库)中获取当前的 IAuthSession从 ServiceStackController 派生的 Controller 。
相关类在 Funq 上注册到 ReuseScope.Request 范围(即基于每个 HTTP 请求),理想情况下,我希望它的每个实例都使用构造函数参数与当前 IAuthSession Autowiring 或公共(public)属性(property)。
我该怎么做?
<小时/>更新
经过一番挖掘,我想出了我认为可能有效的方法。
在我的 AppHost.Configure
中,我注册了一个从当前请求返回 session 的 lambda:
container.Register<IAuthSession>(c =>
HttpContext.Current.Request.ToRequest().GetSession());
另外:
container.RegisterAutoWired<EFCatalogDb>();
其中 EFCatalogDb
是我的 EF 上下文,它采用 IAuthSession
作为构造函数参数:
public class EFCatalogDb : DbContext
{
public EFCatalogDb(IAuthSession session) : base()
{ }
// ...etc....
}
不幸的是,我的开发阶段还没有到可以测试此解决方法的阶段,因此必须询问其他人这是否有意义。
最佳答案
我的第一个建议是尝试将 IAuthSession 排除在数据库类之外,因为这会创建对 ServiceStack 的依赖,这似乎是不必要的。
话虽这么说,我认为您可以采取注册 IAuthSession 并让容器自动注入(inject) IAuthSession 的路线。更好的方法可能是围绕 IAuthSession 创建您自己的“包装类”并将其注入(inject)到您的数据库类中。这将打破对 ServiceStack 的依赖。
如果您没有问题保持对 ServiceStack 的依赖,另一种可能性是使用 SessionFeature
类并执行类似的操作
var key = SessionFeature.GetSessionKey();
authSession = AppHost.Resolve<ICacheClient>().Get<IAuthSession>(key);
关于asp.net-mvc - 在 ServiceStack/MVC4 中的非 Controller 类中访问 IAuthSession,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17306117/