I have an existing application using the last build from the 2.x version of Structuremap, and it works fine. StructureMap 3 just went live recently and I decided to try updating to it and see how it goes.
However no matter what I do, I can't seem to get it to correctly resolve the current user. I'm not sure if it's trying to build the dependencies too early in the lifetime of the app or what the deal might be. Because the release so recent, there is pretty much no information out there that I've found to be of any use yet.
The line registering the dependency.
For<HttpContextBase>().Use(() => new HttpContextWrapper(HttpContext.Current));
For<ICurrentUser>().HybridHttpOrThreadLocalScoped().Use(x => GetCurrentUser(x));
My method to resolve the dependency
private ICurrentUser GetCurrentUser(IContext context)
{
try
{
var httpContext = context.GetInstance<HttpContextBase>();
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, user.Identity.Name);
}
catch (Exception ex)
{
context.GetInstance<ILogger>().Error("Error trying to determine the current user.", ex);
throw new Exception("Error trying to determine the current user.", ex);
}
}
My ICurrentUser interface
public interface ICurrentUser
{
Guid UserId { get; }
string UserName { get; }
}
The line calling GetIdentityId()
is basically just an extension method wrapping the logic to check for the UserId stored on the Identity as a claim item of type ClaimTypes.NameIdentifier
, handling nulls and coalescing to Guid, etc.
Has anyone else tried using StructureMap3 in a webapp for something like this yet?