17

I am trying to set up my Dependency Injection and I am in the need of injecting a IAuthenticationManager from ASP.NET Identity to an OwinContext.

For this I am from my Global.asax -> ServiceConfig.Configure() running:

 container.Register(() => HttpContext.Current.GetOwinContext().Authentication);

But when I am running my application I get this message:

No owin.Environment item was found in the context

Why is this HttpContext.Current.GetOwinContext() not available from Global.asax?

Startup.cs

[assembly: OwinStartupAttribute(typeof(MyApp.Web.Startup))]
namespace Speedop.Web
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }
    }
}

Startup.Auth.cs

public partial class Startup
{
    public void ConfigureAuth(IAppBuilder app)
    {
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<UserManager<User, int>, User, int>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentityCallback: (manager, user) => manager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie),
                    getUserIdCallback: (id) => (Int32.Parse(id.GetUserId()))
                    )
            }
        });

        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
    }
}
janhartmann
  • 14,713
  • 15
  • 82
  • 138
  • 1
    look at [this answer](http://stackoverflow.com/questions/20168978/do-i-need-a-global-asax-cs-file-at-all-if-im-using-an-owin-startup-cs-class-and). Mainly, Global.asax is called before Startup.cs – Jonesopolis Jul 09 '14 at 17:46
  • Hm, I do have 'Microsoft.Owin.Host.SystemWeb.dll' in my directory. I tried moving everything to Startup.cs from my Global.asax after I did ConfigureAuth(...) still the same message comes. – janhartmann Jul 09 '14 at 18:05
  • I just tried creating a whole new sample app and tried getting the OwinContext with the same results. There must be a way :-) – janhartmann Jul 09 '14 at 18:36
  • 1
    [Here's a discussion](https://simpleinjector.codeplex.com/discussions/539965) about Owin with Simple Injector. Perhaps that helps. – Steven Jul 11 '14 at 06:25
  • Thanks @Steven, I will try when I get home and let you know. :-) – janhartmann Jul 11 '14 at 07:22
  • Unfortunately it did not work, maybe I should find another solution on how to inject a IAuthenticationManager into my service. – janhartmann Jul 12 '14 at 06:50

1 Answers1

12

I fixed this with the following:

container.RegisterPerWebRequest(() =>
{
    if (HttpContext.Current != null && HttpContext.Current.Items["owin.Environment"] == null && container.IsVerifying())
    {
        return new OwinContext().Authentication;
    }
    return HttpContext.Current.GetOwinContext().Authentication;

});

Seems like the OwnContext is not present at startup, so I'll wait for it and inject it once its present. Please note that the container.IsVerifying() is present in SimpleInjector.Advanced

janhartmann
  • 14,713
  • 15
  • 82
  • 138
  • What is this "RegisterPerWebRequest()" ? where do you get it from ? Unity doesn't seem to have such a method or extention – Marty Dec 31 '14 at 13:34
  • Found it. You're using SimpleInjector. ok. Question is how do You register the type. For example, controller needs a repo, that need the IauthManager. – Marty Dec 31 '14 at 14:24
  • Does anyone know how to do this with Castle Windsor? – mayabelle Mar 10 '15 at 19:05
  • 1
    In Castle windsor you can do the following: container.Register(Component.For().UsingFactoryMethod( () => { if (HttpContext.Current != null && HttpContext.Current.Items["owin.Environment"] == null) { return new OwinContext().Authentication; } return HttpContext.Current.GetOwinContext().Authentication; }).LifestylePerWebRequest()); – Ron Sijm Mar 16 '15 at 14:57