开发者

ASP.NET MVC + Unity 2.0: lazy loading dependency properties?

开发者 https://www.devze.com 2023-03-09 01:33 出处:网络
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.

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 BackendWrapp开发者_如何学编程er 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消