ASP.NET MVC + Unity 2.0: Lazy Download Dependency Properties?

What I want to do Unity 2.0 to create what I need, getting new properties from configurations all the time, is a little difficult to explain.

This is basically 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 to do is that whenever someone needs an IBackendWrapper, the unity should then get a Session ["UserIdent"] and populate BackendWrapper with this information.

Now Unity loads this information only once and always returns a new UserIdent, even if I have a user ID 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?

+3
source share
1 answer

Yes, it is supported in Unity. You need to register UserIdentwith InjectionFactoryso that it is evaluated at each resolution.

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>())
    );

How you registered it HttpContext.Current.Sessionwas evaluated at the time of registration, which is supposedly located in Global.asax before your session was set up.

+3
source

All Articles