如果你想使用Unity,你必须稍微改变你的实现。您必须将控制器定义为:
public class MyController : Controller
{
private IState _state;
public MyController(IState state)
{
_state = state;
}
[HttpGet]
public ActionResult Index()
{
// Fill the state but you cannot change instance!
_state.A = ...;
_state.B = ...;
return View();
}
[HttpPost]
public ActionResult Change()
{
// Fill the state but you cannot change instance!
_state.A = ...;
_state.B = ...;
return View();
}
}
现在您需要两个额外的步骤。您必须使用PerSessionLifetime管理器来解析IState
,并且必须配置Unity来解析控制器及其依赖项 - 有一些build in support for resolving in ASP.NET MVC 3。
Unity不提供PerSessionLifetime管理器,因此您必须构建自己的。
public class PerSessionLifetimeManager : LifetimeManager
{
private readonly Guid _key = Guid.NewGuid();
public override object GetValue()
{
return HttpContext.Current.Session[_key];
}
public override void SetValue(object newValue)
{
HttpContext.Current.Session[_key] = newValue;
}
public override void RemoveValue()
{
HttpContext.Current.Session.Remove(_key);
}
}
配置控制器也可以在统一配置配置扩展,并定义时,您可以使用此生你的IState
:
<configuration>
<configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />
</configSections>
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<alias alias="perSession" type="NamespaceName.PerSessionLifetimeManager, AssemblyName"/>
<alias alias="IState" type="NamespaceName.IState, AssemblyName" />
<alias alias="State" type="NamespaceName.State, AssemblyName" />
<container name="Web">
<register type="IState" mapTo="State" >
<lifetime type="perSession" />
</register>
</container>
</unity>
</configuration>
工程就像一个魅力。谢谢!我正在做Global.asax中的Unity设置(代码而不是配置),所以我做了'container.RegisterType(新的PerSessionLifetimeManager());' –
2011-05-17 09:19:27
嗯,实际上,我想我可能有错过了什么。如果我在我的控制器中改变'State'类,它是如何被保存回'Session'的? – 2011-05-17 10:14:36
您只能更改属性。你不能改变实例。 – 2011-05-17 10:16:50