Ada*_*ger 5 asp.net-mvc dependency-injection unity-container asp.net-mvc-5
我已经阅读并谷歌搜索了这方面的所有内容,但似乎无法让它发挥作用。LifetimeManager我根据这些帖子在我的 MVC5 应用程序中为 Unity创建了自定义:
这是我的SessionLifetimeManager
public class SessionLifetimeManager : LifetimeManager
{
private string key = Guid.NewGuid().ToString();
public override object GetValue()
{
return HttpContext.Current.Session[key];
}
public override void RemoveValue()
{
HttpContext.Current.Session.Remove(key);
}
public override void SetValue(object newValue)
{
HttpContext.Current.Session[key] = newValue;
}
}
Run Code Online (Sandbox Code Playgroud)
我只有几种类型,以下是UnityConfig.cs中的相关注册:
container.RegisterType<IEpiSession, EpiSession>(new SessionLifetimeManager(),
new InjectionConstructor(config.AppServerURI, config.PathToSysConfig));
container.RegisterType<IReportRepository, EpicorReportRepository>(new TransientLifetimeManager());
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
Run Code Online (Sandbox Code Playgroud)
请注意,它EpicorReportRepository依赖于IEpiSession通过构造函数注入。
public class EpicorReportRepository : IReportRepository
{
private IEpiSession session;
// DI constructor
public EpicorReportRepository(IEpiSession session) {
this.session = session;
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
我的问题:第一个用户/会话连接到应用程序后,此后的每个新用户/会话似乎仍在使用EpiSession第一个用户为他创建/注入的对象和凭据。这似乎是互联网上使用的常见模式,所以我想知道我错过了什么。
你如何测试IEpiSession不同的情况是否相同Session?
尝试从不同的浏览器打开您的应用程序。如果您在同一浏览器中打开多个选项卡,则使用相同的会话。
我检查了你的代码,它对我有用。唯一的区别在于SetResolver():
DependencyResolver.SetResolver(
type => container.Resolve(type),
types => container.ResolveAll(types));
Run Code Online (Sandbox Code Playgroud)
完整的注册代码如下:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
...
var container = new UnityContainer();
container.RegisterType<IEpiSession, EpiSession>(
new SessionLifetimeManager(),
new InjectionConstructor("config.AppServerURI", "config.PathToSysConfig"));
container.RegisterType<IReportRepository, EpicorReportRepository>(new TransientLifetimeManager());
DependencyResolver.SetResolver(
type => container.Resolve(type),
types => container.ResolveAll(types));
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1791 次 |
| 最近记录: |