Search code examples
asp.net-mvcdependency-injectioncastle-windsor

Castle Windsor life style depend on forms authentication with cookie


I have a user class in my framework and I want to initial the first time when login.

   public  class UserClass
{
    public  void Initial(string userId, string userName)
    {

        UserId = useriId;
        UserName = userName;

    }

    public  string UserId { get; private set; }
    public  string UserName { get; private set; }
}

I want life this class depend on

HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName]

Solution

  • I'm not sure if your Initial method is meant to be a constructor for UserClass or an init function. You might approach the solution differently depending on that. In either case, there's three ways I'd consider approaching this:

    1. Explicitly (constructor)

    Build a wrapper service exposing the values from cookies and make your UserClass consume that. It's the simplest, least magical option that will be easy for anyone on your team to grasp.

    1. DynamicParameters (constructor)

    Use the DynamicDependencies feature to pass the cookie values through to the resolution pipeline. It ties you to Windsor and may not be super-obvious to every person on your team so you need to consider that.

    1. OnCreate (init)

    Use the OnCreate feature to initialise the object post-construction. Pretty much the same idea as option 2, but used on an already-constructed object. This can work applying either explicit or implicit approach (that is 1. or 2. from above)

    Like with everything, it's all a trade-off between what is technically possible and what makes sense for your code architecture and team.