Register IAuthenticationManager with Simple Injector

后端 未结 3 1236
春和景丽
春和景丽 2020-11-30 03:40

I am having a configuration setup for Simple Injector where I have moved all of my registrations to OWIN pipeline.

Now the problem is I have a controller Acco

3条回答
  •  -上瘾入骨i
    2020-11-30 04:09

    See my answer here.

    Although you are accessing a different type, the problem is the same. You cannot rely on properties of HttpContext during application startup because the application is initialized outside of the user's context. The solution is to make an abstract factory to read the values at runtime rather than at object creation and inject the factory rather than the IAuthenticationManager type into your controller.

    public class AccountController
    {
        private readonly AngularAppUserManager _userManager;
        private readonly AngularAppSignInManager _signInManager;
        private readonly IAuthenticationManagerFactory _authenticationManagerFactory;
    
        public AccountController(AngularAppUserManager userManager
          , AngularAppSignInManager signinManager
          , IAuthenticationManagerFactory authenticationManagerFactory)
        {
            this._userManager = userManager;
            this._signInManager = signinManager;
            this._authenticationManagerFactory = authenticationManagerFactory;
        }
    
        private IAuthenticationManager AuthenticationManager
        {
            get { return this._authenticationManagerFactory.Create(); }
        }
    
        private void DoSomething()
        {
            // Now it is safe to call into HTTP context
            var manager = this.AuthenticationManger;
        }
    }
    
    public interface IAuthenticationMangerFactory
    {
        IAuthenticationManger Create();
    }
    
    public class AuthenticationMangerFactory
    {
        public IAuthenticationManger Create()
        {
            HttpContext.Current.GetOwinContext().Authentication;
        }
    }
    
    // And register your factory...
    container.Register();
    

提交回复
热议问题