Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
448 views
in Technique[技术] by (71.8m points)

c# - Using ASP.NET Session for Lifetime Management (Unity)

I am considering using Unity to manage the lifetime of a custom user class instance. I am planning on extending the LifetimeManager with a custom ASP.NET session manager. What I want to be able to do is store and retrieve the currently logged in user object from my custom classes, and have Unity get the instance of User from the session object in ASP.NET, or (when in a Win32 project) retrieve it statically or from the current thread.

So far my best solution is to create a static instance of my Unity container on startup, and use the Resolve method to get my User object from each of my classes. However, this seems to create a dependency on the unity container in my other classes. What is the more "Unity" way of accomplishing this goal? I would like to be able to read/replace the current User instance from any class.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You'd get the best bang with Unity when used with ASP.Net MVC rather than the plain old ASP.Net project. ASP.Net MVC allows you to use a container like Unity to manage the user objects, controllers, models, etc. If possible, use MVC rather than ASP.net web forms for your projects.

If I understand your question correctly, you would want to use Unity to maintain the lifetime of the object to per session. You need to implement a SessionLifetimeManager that extends LifetimeManager. The code is pretty simple and goes along these lines:

public class SessionLifetimeManager : LifetimeManager
{
    private string _key = Guid.NewGuid().ToString();

    public override object GetValue()
    {
          return HttpContext.Current.Session[_key];
    }

    public override void SetValue(object value)
    {
          HttpContext.Current.Session[_key] = value;
    }

    public override void RemoveValue()
    {
          HttpContext.Current.Session.Remove(_key);
    }
}

You could also write a similar one for PerWebRequest lifetime management.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...