オブジェクトコンテキストの5処分:現在ASP MVC私は次のようにユーザー権限をチェックするために、データベースを照会する必要が拡張メソッド持って
public static bool HasPermission(this IPrincipal user, string permission)
{
ApplicationUser appUser = ApplicationUserManager.GetUser(user.Identity.GetUserId());
return appUser.HasPermission(permission);
}
アプリケーションユーザを取得するための呼び出しを次のように実装された:
public static ApplicationUser GetUser(string userId)
{
return GetUser(new ApplicationDbContext(), userId);
}
public static ApplicationUser GetUser(ApplicationDbContext context, string userId)
{
ApplicationUser _retVal = null;
try
{
_retVal = context.Users.Where(p => p.Id == userId).FirstOrDefault();
}
catch (Exception)
{
}
return _retVal;
}
私のビューとコントローラのアクションで、私は頻繁にUser.HasPermission()メソッドを呼び出します。だから私は頻繁にこのメソッドを呼び出すことのパフォーマンスの含意を検討しています。コンテキストを破棄するように、次のようにusingステートメント内にラップしてコールを実装する方が良いでしょうか、すでに上で実装した方法で正しいですか?
public static bool HasPermission(this IPrincipal user, string permission)
{
using (ApplicationDbContext _context = new ApplicationDbContext())
{
var userId = user.Identity.GetUserId();
ApplicationUser applicationUser = _context.Users.Where(p => p.Id == userId).FirstOrDefault();
return applicationUser.HasPermission(permission);
}
}
データベースには何人のApplicationUserがいますか?この数字が増えたり、かなり似ていると思いますか?あなたの 'hasPermission'のアプリケーションはうまく見えます、それはガベージコレクタがブロックの最後にコンテキストオブジェクトを破壊することを保証し、メモリを解放します。ただし、同じユーザーのアクセス権を何度も確認している場合は、データベースを常に再クエリするのではなく、そのオブジェクトをメモリに保存する価値があります。 – gudthing
@gudthingなので、それを使用ブロックにまとめる必要はありませんか?ユーザー数は500-1000人の間で増加します。 – adam78
@ gudthingあなたはそれをどのようにメモリに保存しようと思いますか?いくつかのコードサンプルが説明するのに役立ちますか? – adam78