好吧,我之前的问题/设置有太多变量,所以我将其精简为最基本的组件。
给出使用 StructureMap3 的以下代码...
//IoC setup
For<HttpContextBase>().UseSpecial(x => x.ConstructedBy(y => HttpContext.Current != null ? new HttpContextWrapper(HttpContext.Current) : null ));
For<ICurrentUser>().Use<CurrentUser>();
//Classes used
public class CurrentUser : ICurrentUser
{
public CurrentUser(HttpContextBase httpContext)
{
if (httpContext == null) return;
if (httpContext.User == null) return;
var user = httpContext.User;
if (!user.Identity.IsAuthenticated) return;
UserId = httpContext.User.GetIdentityId().GetValueOrDefault();
UserName = httpContext.User.Identity.Name;
}
public Guid UserId { get; set; }
public string UserName { get; set; }
}
public static class ClaimsExtensionMethods
public static Guid? GetIdentityId(this IPrincipal principal)
{
//Account for possible nulls
var claimsPrincipal = principal as ClaimsPrincipal;
if (claimsPrincipal == null)
return null;
var claimsIdentity = claimsPrincipal.Identity as ClaimsIdentity;
if (claimsIdentity == null)
return null;
var claim = claimsIdentity.FindFirst(x => x.Type == ClaimTypes.NameIdentifier);
if (claim == null)
return null;
//Account for possible invalid value since claim values are strings
Guid? id = null;
try
{
id = Guid.Parse(claim.Value);
}
catch (ArgumentNullException) { }
catch (FormatException) { }
return id;
}
}
这怎么可能在“监视”窗口中实现?
I have a web application that I'm upgrading to using StructureMap 3.x from 2.x, but I'm getting odd behavior on specific dependency.
我有一个 ISecurityService,当用户请求页面时,我用它来验证一些事情。该服务依赖于一个我称为 ICurrentUser 的小接口。类的实现非常简单,实际上它可以是一个结构。
public interface ICurrentUser
{
Guid UserId { get; }
string UserName { get; }
}
这是使用以下代码通过依赖注入获得的。
For<ICurrentUser>().Use(ctx => getCurrentUser(ctx.GetInstance<HttpContextBase>()));
For<HttpContextBase>().Use(() => getHttpContext());
private HttpContextBase getHttpContext()
{
return new HttpContextWrapper(HttpContext.Current);
}
private ICurrentUser getCurrentUser(HttpContextBase httpContext)
{
if (httpContext == null) return null;
if (httpContext.User == null) return null; // <---
var user = httpContext.User;
if (!user.Identity.IsAuthenticated) return null;
var personId = user.GetIdentityId().GetValueOrDefault();
return new CurrentUser(personId, ClaimsPrincipal.Current.Identity.Name);
}
当请求进来时,我的站点范围的身份验证首先发生,这取决于ISecurityService
。这发生在 OWIN 内部并且似乎发生在之前HttpContext.User
已填充,所以为空,就这样吧。
后来,我有一个 ActionFilter 来检查,通过ISecurityService
,如果当前用户已同意网站当前版本的使用条款,如果没有,他们将被重定向到首先同意的页面。
这一切在 Structuremap 2.x 中都运行良好。为了迁移到 StructureMap3,我安装了 Nuget 包 StructureMap.MVC5 以帮助加快速度。
当我的代码到达 ActionFilter 中用于检查使用条款的行时,我得到了这个。
var securityService = DependencyResolver.Current.GetService<ISecurityService>();
agreed = securityService.CheckLoginAgreedToTermsOfUse();
代替CheckLoginAgreedToTermsOfUse()
,我的实例CurrentUser
一片空白。尽管它会成功,但我在 getCurrentUser() 内部的断点似乎从未被击中。这几乎就像是一个已成定局的事情,因为上次它是空的,尽管这次它会得到解决。
我有点困惑为什么getCurrentUser()
从未被要求请求ISecurityService
。我什至尝试明确地坚持.LifecycleIs<UniquePerRequestLifecycle>()
在我的连接上进行处理ICurrentUser
没有效果。