1

I have seen this code very often.

Why is there a null check for the _AppRoleManager? Why not just return AppRoleManager?

public class BaseApiController : ApiController
{
    //Code removed from brevity
    private ApplicationRoleManager _AppRoleManager = null;

    protected ApplicationRoleManager AppRoleManager
    {
        get
        {
            return _AppRoleManager ?? Request.GetOwinContext().GetUserManager<ApplicationRoleManager>();
        }
    }
}
Pascal
  • 12,265
  • 25
  • 103
  • 195
  • That code does not make sense. Are you sure you aren't missing a vital part? Like a `_AppRoleManager =` in the getter? – nvoigt Aug 21 '15 at 20:08
  • [null-coalescing operator](https://msdn.microsoft.com/en-us/library/ms173224.aspx) – Chef_Code Apr 20 '16 at 03:15

3 Answers3

0

Why would you want to return _AppRoleManager here (I assume that's what you want and a missing underscore is just a typo)? Clearly, there are two possible things that the property can return: an object whose reference is stored in a private field and a result of a method call. We can't see the rest of the code, but one possible situation I can think of is that when you create an instance of the class, you can pass a variable of AppRoleManager type to a constructor and instantiate the field of the class with that variable. And if you don't have anything to pass, then you use the default constructor. In such scenario invoking the getter will result in some default ApplicationRoleManager being returned.

Kapol
  • 6,383
  • 3
  • 21
  • 46
0

The null check is often used alongside the two constructors found in the default template ASP.NET Identity classes (one parameterless, the other often taking a manager and sign in manager).

For example, if you did not set the role manager manually using the constructor or through DI, the null check will then get the role manager assigned to that OWIN context.

Scott Brady
  • 5,498
  • 24
  • 38
0

In this code Request.GetOwinContext().GetUserManager<ApplicationRoleManager>() is local default (aka good local default) of ApplicationRoleManager. You could set ApplicationRoleManager but if you don't do that object uses its local default. In other words BaseApiController has a optional dependency with ApplicationRoleManager.

This pattern known as Property Injection pattern. By using Property Injection you could easily deal with optional dependencies instead of Constructor Injection. For more info read "Is there an alternative to bastard injection" question.

Community
  • 1
  • 1
Sam FarajpourGhamari
  • 14,601
  • 4
  • 52
  • 56
  • the code is from here: http://bitoftech.net/2015/03/11/asp-net-identity-2-1-roles-based-authorization-authentication-asp-net-web-api/ – Pascal Aug 21 '15 at 23:39
  • My answer still true. In this example dependency injection restricted to parent class. Inherited classes can not set dependency. – Sam FarajpourGhamari Aug 22 '15 at 07:20