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

1

6

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?

Donofrio answered 3/4, 2014 at 18:46 Comment(0)
K
1

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.

Kerri answered 16/4, 2014 at 13:10 Comment(1)
I saw that too, but this is with the new StructureMap.Web package installed. I'll take another look as soon as I have time to try it out again.Donofrio

© 2022 - 2024 — McMap. All rights reserved.