8

Używam identyfikatora asp.net w moim projekcie i korzystam z frameworkmap jako struktury DI. Problem jest, gdy używam konstruktora wtrysku następnie ApplicationUserManager nie ustawił wszystkich jego członków, np TokenProvider ...Jak skonfigurować aplikację ASP.NET Identity ApplicationUserManager za pomocą struktury StructureMap

to moja klasa ApplicationUserManager:

public class ApplicationUserManager : UserManager<User, long> 
{ 
    public ApplicationUserManager(IUserStore<User, long> store) 
     : base(store) 
    { 
    } 

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
    { 
     var manager = new ApplicationUserManager(new CustomUserStore(context.Get<InsuranceManagementContext>())); 

     // Configure the application user manager 
     manager.UserValidator = new UserValidator<User, long>(manager) 
     { 
      AllowOnlyAlphanumericUserNames = false, 
      RequireUniqueEmail = false 
     }; 

     manager.PasswordValidator = new PasswordValidator 
     { 
      RequireDigit = true, 
      RequiredLength = 8, 
      RequireLowercase = false, 
      RequireNonLetterOrDigit = true, 
      RequireUppercase = false 
     }; 

     var dataProtectionProvider = options.DataProtectionProvider; 
     if (dataProtectionProvider != null) 
     { 
      manager.UserTokenProvider = 
       new DataProtectorTokenProvider<User, long>(dataProtectionProvider.Create("TEST")); 
     } 

     return manager; 
    } 
} 

to Startup.Auth klasa:

public partial class Startup 
{ 
    // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 
    public void ConfigureAuth(IAppBuilder app) 
    { 
     app.CreatePerOwinContext(InsuranceManagementContext.Create); 
     app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create); 

     // Enable the application to use a cookie to store information for the signed in user 
     app.UseCookieAuthentication(new CookieAuthenticationOptions 
     { 
      ExpireTimeSpan = TimeSpan.FromHours(2.0), 
      AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active, 
      AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, 
      LoginPath = new PathString("/Account/Login"), 
     }); 
    } 
} 

i jej mój AccountController:

public class AccountController : BaseController 
{ 
    private ApplicationUserManager _userManager; 
    public ApplicationUserManager UserManager 
    { 
     get 
     { 
      return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); 
     } 
     private set 
     { 
      _userManager = value; 
     } 
    } 

    public AccountController(ApplicationUserManager userManager) 
    { 
     UserManager = userManager; 
    } 
} 

moje qu estion jest jak mogę skonfigurować mój ApplicationUserManager z structuremap? Jeżeli ustawić go jak poniżej kod działa, ale nie wiem, jest to dobre rozwiązanie, czy nie:

ObjectFactory.Initialize(x => 
{ 
    ... 
    x.For<ApplicationUserManager>().Use(() => HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>()); 
    ... 
}); 

proszę schować mnie, czy istnieje lepsze rozwiązanie i jeśli jest ok to co jest najlepsze życie na to? HttpContextScope, Singleton, ...?

+2

Właśnie napisałem bloga o kontenerach tożsamości i kontach DI: http://tech.trailmax.info/2014/09/aspnet-identity-and-ioc-container-registration/ to prawdopodobnie ci pomoże. – trailmax

Odpowiedz

5

Zanim utworzysz konfigurację StructureMap, będziesz wiedzieć, w jaki sposób utworzyć ją ręcznie, tj., Jeśli faktycznie wszystko samodzielnie wykonasz "samodzielnie".

UserManager ma zależność od IUserStore, a jej implementacja EntityFramework (UserStore) ma zależność od DbContext. robi wszystko ręcznie będzie wyglądać następująco:

var dbContext = new IdentityDbContext("Your ConnectionString Name"); 
var userStore = new UserStore<IdentityUser>(dbContext); 
var userManager = new UserManager<IdentityUser>(userStore); 

(Wymień IdentityUser z niestandardowego użytkownika, jeśli używasz jednego)

Następnie można skonfigurować UserManager takiego:

userManager.PasswordValidator = new PasswordValidator 
{ 
    RequiredLength = 6 
}; 

The najbardziej skomplikowana część dotycząca konfigurowania userManager jest powiązana z UserTokenProvider (który używa api ochrony danych), jeśli zrobiłbyś to ręcznie to byłby look like this:

var dataProtectionProvider = new DpapiDataProtectionProvider("Application name"); 
var dataProtector = dataProtectionProvider.Create("Purpose"); 
userManager.UserTokenProvider = new DataProtectorTokenProvider<IdentityUser>(dataProtector); 

Oto przykład z rejestru StructureMap (można ekstrapolować z tego przykładu i dostosować go do własnych potrzeb):

public DefaultRegistry() { 
     Scan(
      scan => { 
       scan.TheCallingAssembly(); 
       scan.WithDefaultConventions(); 
       scan.With(new ControllerConvention()); 
      }); 


     For<IUserStore<IdentityUser>>() 
      .Use<UserStore<IdentityUser>>() 
      .Ctor<DbContext>() 
      .Is<IdentityDbContext>(cfg => cfg.SelectConstructor(() => new IdentityDbContext("connection string")).Ctor<string>().Is("IdentitySetupWithStructureMap")); 

     ForConcreteType<UserManager<IdentityUser>>() 
      .Configure 
      .SetProperty(userManager => userManager.PasswordValidator = new PasswordValidator 
      { 
       RequiredLength = 6 
      }) 
      .SetProperty(userManager => userManager.UserValidator = new UserValidator<IdentityUser>(userManager));     
    } 

pisałem bloga post about this, wyjaśnia proces, który doprowadzi do tego konfiguracja, istnieje również link to an example on github of an MVC project, gdzie za pomocą tej konfiguracji można tworzyć, wyświetlać i usuwać użytkowników.

Powiązane problemy