ASP.NET MVC + Unity 2.0:延迟加载依赖属性?

发布于 2024-11-11 06:55:20 字数 565 浏览 0 评论 0原文

我希望 Unity 2.0 做的是通过始终从配置中获取新属性来实例化我需要的东西,这有点难以解释。

基本上这就是我想要做的:

global.asax

container.RegisterType<IBackendWrapper, BackendWrapper>(new InjectionProperty("UserIdent", (HttpContext.Current.Session == null ? new UserIdent() : HttpContext.Current.Session["UserIdent"] as UserIdent)));           

我想要做的是,每当有人需要 IBackendWrapper 时,unity 就应该获取 Session["UserIdent"] 并用该信息填充 BackendWrapper 。

现在,Unity 只加载此信息一次,即使我在会话中存储了用户标识,它也总是返回一个新的 UserIdent。有没有办法在 Unity 2.0 中实现这种行为?或者它是否受到另一个 IoC 框架(如 NInject)的支持?

What i want Unity 2.0 to do is to instantiate what i need by getting the new properties from the configurations all the time, a bit hard to explain.

Basically this is what i want to do:

global.asax

container.RegisterType<IBackendWrapper, BackendWrapper>(new InjectionProperty("UserIdent", (HttpContext.Current.Session == null ? new UserIdent() : HttpContext.Current.Session["UserIdent"] as UserIdent)));           

What i want this to do is that whenever someone needs an IBackendWrapper, unity should then get the Session["UserIdent"] and populate the BackendWrapper with that information.

Right now unity only loads this information once and it always returns a new UserIdent even when i have an User ident stored in the session. Is there a way to get this behavior in Unity 2.0? or is it supported by another IoC framework like NInject?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

等待我真够勒 2024-11-18 06:55:20

是的,Unity 中支持它。您需要向 InjectionFactory 注册 UserIdent ,以便在每次解析时对其进行评估。

container
    .RegisterType<UserIdent>(new InjectionFactory(c =>
    {
        return HttpContext.Current.Session == null
            ? new UserIdent()
            : HttpContext.Current.Session["UserIdent"] as UserIdent;
    }));

container
    .RegisterType<IBackendWrapper, BackendWrapper>(
        new InjectionProperty("UserIdent", new ResolvedParameter<UserIdent>())
    );

按照您注册的方式,HttpContext.Current.Session 在您进行注册时正在评估,这可能在会话设置之前位于 Global.asax 中。

Yes, it's supported in Unity. You need to register UserIdent with an InjectionFactory so it's evaluated on each resolve.

container
    .RegisterType<UserIdent>(new InjectionFactory(c =>
    {
        return HttpContext.Current.Session == null
            ? new UserIdent()
            : HttpContext.Current.Session["UserIdent"] as UserIdent;
    }));

container
    .RegisterType<IBackendWrapper, BackendWrapper>(
        new InjectionProperty("UserIdent", new ResolvedParameter<UserIdent>())
    );

The way you were registering it, HttpContext.Current.Session was being evaluated at the time you did the registration which is presumably in Global.asax before your session was set up.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文