تزریق وابستگیهای رایج ASP.NET MVC به برنامه
نویسنده: سیروان عفیفی
تاریخ: ۱۳۹۴/۰۵/۱۷ ۲۳:۳۰
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
var userId= User.Identity.GetUserId(); var user = _context.Users.Find(userId); var user = int.Parse(User.Identity.GetUserId());
public class CommonASPNETRegistry : StructureMap.Configuration.DSL.Registry
{
public CommonASPNETRegistry()
{
For<IIdentity>().Use(() => HttpContext.Current.User.Identity);
// Other dependencies
}
} public static class SmObjectFactory
{
private static readonly Lazy<Container> _containerBuilder =
new Lazy<Container>(defaultContainer, LazyThreadSafetyMode.ExecutionAndPublication);
public static IContainer Container
{
get { return _containerBuilder.Value; }
}
private static Container defaultContainer()
{
return new Container(ioc =>
{
// Other settings
ioc.AddRegistry(new CommonASPNETRegistry());
});
}
} var user = int.Parse(User.Identity.GetUserId());
public interface ICurrentUser
{
ApplicationUser User { get; }
} public class CurrentUser : ICurrentUser
{
private readonly IIdentity _identity;
private readonly IApplicationUserManager _userManager;
private ApplicationUser _user;
public CurrentUser(IIdentity identity, IApplicationUserManager userManager)
{
_identity = identity;
_userManager = userManager;
}
public ApplicationUser User
{
get { return _user ?? (_user = _userManager.FindById(int.Parse(_identity.GetUserId()))); }
}
} public class HomeController : BaseController
{
private readonly ICurrentUser _currentUser;
public HomeController(ICurrentUser user)
{
_user = user;
}
public ActionResult Index()
{
// user
var user = _currentUser.User;
// user id
var userId = _currentUser.User.Id;
}
} ioc.For<IIdentity>()
.Use(
() =>
(HttpContext.Current != null && HttpContext.Current.User != null)
? HttpContext.Current.User.Identity
: null);
private readonly ICurrentUser _currentUser;
public HomeController(ICurrentUser user)
{
_user = user;
} private readonly ICurrentUser _currentUser;
public HomeController(ICurrentUser user)
{
_currentUser = user;
} public class CurrentUser : ICurrentUser
{
private readonly IIdentity _identity;
public CurrentUser(IIdentity identity)
{ public class CurrentUser : ICurrentUser
{
private readonly Lazy<Func<IIdentity>> _identity;
public CurrentUser(Lazy<Func<IIdentity>> identity)
{
_identity = identity;
}
public int GetCurrentUserId()
{
return _identity.Value().GetUserId<int>();
}