0

I want to ask Owin if a user exists. Putting together random stuff I've found online, I end up with this (totally untested code):

/// <summary> Returns true if the TestUser user exists in the membership database. </summary>
public static bool UserExists(ApplicationDbContext db, string username)
{
    var userManager = new Microsoft.AspNet.Identity.UserManager<ApplicationUser>(
        new Microsoft.AspNet.Identity.EntityFramework.UserStore<ApplicationUser>(db));

    var user = userManager.FindByName(username);
    return (user != null);
}

My question is, do I really need that long, ugly expression to get a new UserManager? Or is there a better, more efficient, cleaner, or more correct way to do this?

And now that I look a little more closely at it, I see that both UserManager and UserStore are disposable. Do I want to wrap things in using blocks?

Bob.at.Indigo.Health
  • 11,023
  • 13
  • 64
  • 111

1 Answers1

0

It's the same as creating most any object, but in this case I would add some using statements to simplify it:

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;

Which would make your instantiation statement much tidier:

var userManager = new UserManager<ApplicationUser>(
    new UserStore<ApplicationUser>(db));
DavidG
  • 113,891
  • 12
  • 217
  • 223
  • But now that I look a little deeper, I see that the UserManager object has a Dispose method. Should I wrap it in a `using` block? And for that matter, UserStore is also disposable... – Bob.at.Indigo.Health May 28 '14 at 01:30
  • 1
    Personally I wouldn't do any of this and would instead use a DI framework. – DavidG May 28 '14 at 01:37