Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency injection of the current User in an MVC application using StructureMap3

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?

like image 351
Nick Albrecht Avatar asked Apr 03 '14 18:04

Nick Albrecht


1 Answers

Having run into this problem myself, it appears that every web related within StructureMap has been moved into a separate Nuget package called StructureMap.Web that can be found here.

I presume this is because StructureMap 3 is now PLC (Portalble Class Library) compliant, so moving it into a separate package would make sense.

Once you include that package, everything should continue to work as normal.

like image 190
Joseph Woodward Avatar answered Nov 15 '22 09:11

Joseph Woodward