如果你想使用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