我是MVC4 C#网站。 我有构造函数的基本控制器
public BaseController(IUnityContainer container, SessionContext context)
问题是容器是全局共享的,当我尝试解析或注册对象时,它们通过会话共享。另一方面,SessionContext(参数)仅对用户会话是唯一的。 我希望容器对于用户会话来说是唯一的(为了能够为用户会话解析唯一对象),但我不知道如何实现它。 我有UnityControllerFactory,如下所示:
public class UnityControllerFactory : DefaultControllerFactory
{
private IUnityContainer container;
public UnityControllerFactory(IUnityContainer container){
this.container = container;
this.RegisterTypes();
}
protected override IController GetControllerInstance(RequestContext context, Type controllerType)
{
if (controllerType != null)
{
return this.container.Resolve(controllerType) as IController;
}
return null;
}
private void RegisterTypes(){
container.RegisterType<SessionContext>(new UnityPerSessionLifetimeManager("private.SessionContext"));
container.RegisterType<DataService>(new UnityPerSessionLifetimeManager("private.Service"));
}
}
和终身经理
public class UnityPerSessionLifetimeManager : LifetimeManager
{
private string sessionKey;
public UnityPerSessionLifetimeManager(string sessionKey)
{
this.sessionKey = sessionKey;
}
public override object GetValue()
{
return HttpContext.Current.Session[this.sessionKey];
}
public override void RemoveValue()
{
HttpContext.Current.Session.Remove(this.sessionKey);
}
public override void SetValue(object newValue)
{
HttpContext.Current.Session[this.sessionKey] = newValue;
}
}