Register return Type

130 views Asked by At

We have a C# class that holds session values for user in an MVC web application. Now I want to make the class more generic. Until now we have getters and setters for the session like

public class WebAppLogin
{
    public static WebAppLogin Current
    { 
        get; //Gets the current Login from the session
        set; //Sets the current Login to the session
    }
    public UserObject User
    { 
        get; //Gets the value from the session
        set; //Sets the value to the session
    }

    //Method for the UserObject
    public List<String> GetUserRoles()
    {
        //kind of magic stuff
        return userroles;
    }
}

With this class we can access the current user object like this

WebAppLogin.Current.User

I want to write a generic class that allows the developers to register the type of the user object and use this type of object in their projects.

My approach was something like this

public class GenericLogin<T>
{
    public static GenericLogin<T> Current
    { 
        get; //Gets the current Login from the session
        set; //Sets the current Login to the session
    }
    public T User
    {
        get; //Gets the value from the session
        set; //Sets the value to the session
    }
}

Now the developers have to write the type of the User everywhere they want to use it.

My question is, is there some pattern or library (built into .net or free to use commercially) that allows me to register the type of the User at the Application_Start and use this type as the return type for my User Property?

The reason for this is our quite strict naming convention. The User object is almost always the entity class. We would end up with lines like

GenericLogin<ABC01_REGISTERED_USER>.Current.User;

This is what I want to prevent. Is there any solution for this?

1

There are 1 answers

2
Patrick Hofman On BEST ANSWER

If you know the type at startup, you could just derive the class:

public class UserLogin : GenericLogin<ABC01_REGISTERED_USER>
{ }

Then use that class all along. Else, you have to supply the type name every time, since else it can't know that you want to use that type every time.