[RESOLVED]Can this code I found in a controller be simplified?

They say the best way to learn how to code better is to read open source code on projects similar to yours. Which is exactly what I am doing. Basically, I was looking at an account controller class.  I noticed one project wrote the following:

Example A

private AppUserManager UserManager {
            get {
                return HttpContext.GetOwinContext().GetUserManager<AppUserManager>();
            }
}

However, in a similar application, I saw something written as:

Example B

public UserManager<ApplicationUser> UserManager { get; private set;}

Hmmm, that’s interesting. Suppose I wanted to make these statements equivalent to each other? Could I rewrite Example B as follows? Now same as A?

private UserManager<AppUserManager> UserManager {get; }

Is this true for all returns that feature HttpContext.GetOwinContext()?

Hi hlyates,

hlyates

public UserManager<ApplicationUser> UserManager { get; private set;}

This code mean that it can be set in current class.


hlyates

private UserManager<AppUserManager> UserManager {get; }

This code mean that it is read only, we can’t set it.

In my opinion, the better way is that:

private ApplicationUserManager _userManager;
 public ApplicationUserManager UserManager {
            get
            {
                return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
            }
            private set
            {
                _userManager = value;
            }
        }

Best Regards

Starain

simplified could mean alot. maintinance, readability, security, decoupled. If you want that, I suggest private IUserManager<IAppUserManager> {get;}

Starain chen – MSFT

{ return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); } private set { _userManager = value; } }

Can you please explain what ?? is doing here? This is the first time I have seen that. Thanks.

ternary operator for null. its the same as if(_userManager == null){

return HttpContext.blahblah}

Xequence

ternary operator for null. its the same as if(_userManager == null){

return HttpContext.blahblah}

That’s slick. Thanks Xequence. Since I am striving to turn into a power .NET developer. Do you have any books, websites, and or other resources that you use to keep current on .NET MVC? I really value recommendations by word of mouth.

I started with asp.net website and downloaded everything they had to offer. Better to get the info from the horses mouth, so to speak. The books I read are about the theory of it all and once you know the theory, you will find yourself understanding the
code that much more.

Leave a Reply