внедрение зависимостей с использованием Ninject, Identity и asp net MVC5 DDD - PullRequest
0 голосов
/ 25 апреля 2020

Я создаю проект в ASP net стандарте MVC5 DDD с Identity и Ninject, однако я сталкиваюсь с некоторыми трудностями, когда дело доходит до введения зависимостей идентификации.

проект находится в стадии разработки разработано следующим образом:

1) Я отделил идентификацию от «класса» презентации, создав модуль на случай, если у меня есть другие веб-приложения, которые я использую, мне не нужно настраивать все заново и просто вызывать это moulo. 2) Я проделал ту же процедуру с Ninject.

введите описание изображения здесь

У меня есть следующий класс контекста

public class XRMIdentityContext : IdentityDbContext<ApplicationUser>, IDisposable
{
    public XRMIdentityContext()
        : base("XtremeDB", throwIfV1Schema: false)
    {
    }

    public static XRMIdentityContext Create()
    {
        return new XRMIdentityContext();
    }
}

ApplicationUser:

public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }
}

ApplicationRoleManager:

public class ApplicationRoleManager : RoleManager<IdentityRole>
{
    public ApplicationRoleManager(IRoleStore<IdentityRole, string> roleStore)
        : base(roleStore)
    {

    }

    public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
    {
        return new ApplicationRoleManager(new RoleStore<IdentityRole>(context.Get<XRMIdentityContext>()));
    }
}

ApplicationSignInManager:

enter public class ApplicationSignInManager : SignInManager<ApplicationUser, string>
{
    public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager)
        : base(userManager, authenticationManager)
    {
    }

    public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
    {
        return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
    }

    public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context)
    {
        return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
    }
}

ApplicationUserManager:

public class ApplicationUserManager : UserManager<ApplicationUser>
{
    public ApplicationUserManager(IUserStore<ApplicationUser> store)
        : base(store)
    {
        // Configurando validator para nome de usuario
        UserValidator = new UserValidator<ApplicationUser>(this)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        };

        // Logica de validação e complexidade de senha
        PasswordValidator = new PasswordValidator
        {
            RequiredLength = 6,
            RequireNonLetterOrDigit = false,
            RequireDigit = false,
            RequireLowercase = false,
            RequireUppercase = false,
        };

        // Configuração de Lockout
        UserLockoutEnabledByDefault = true;
        DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
        MaxFailedAccessAttemptsBeforeLockout = 5;

        // Providers de Two Factor Autentication
        RegisterTwoFactorProvider("Código via SMS", new PhoneNumberTokenProvider<ApplicationUser>
        {
            MessageFormat = "Seu código de segurança é: {0}"
        });

        RegisterTwoFactorProvider("Código via E-mail", new EmailTokenProvider<ApplicationUser>
        {
            Subject = "Código de Segurança",
            BodyFormat = "Seu código de segurança é: {0}"
        });

        // Definindo a classe de serviço de e-mail
        EmailService = new EmailService();

        // Definindo a classe de serviço de SMS
        SmsService = new SmsService();

        var provider = new DpapiDataProtectionProvider("Teste");
        var dataProtector = provider.Create("ASP.NET Identity");

        UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtector);

    }
}

В целом я настроил его следующим образом:

public class XRMNinject
{
    public IKernel Kernel { get; private set; }

    public XRMNinject()
    {
        Kernel = GetNinjectModules();
        ServiceLocator.SetLocatorProvider(() => new NinjectServiceLocator(Kernel));
    }
    public StandardKernel GetNinjectModules()
    {
        return new StandardKernel(
            new ApplicationNinject(),
            new DomainInfraNinject(),
            new DomainNinject(),
            new IdentityNinject());
    }
}

IdentityNinject:

public class IdentityNinject : NinjectModule
{
    public override void Load()
    {

        Bind<IUserStore<ApplicationUser>>().To<UserStore<ApplicationUser>>();
        Bind<UserManager<ApplicationUser>>().ToSelf();

        Bind<HttpContextBase>().ToMethod(ctx => new HttpContextWrapper(HttpContext.Current)).InTransientScope();

        Bind<ApplicationSignInManager>().ToMethod((context) =>
        {
            var cbase = new HttpContextWrapper(HttpContext.Current);
            return cbase.GetOwinContext().Get<ApplicationSignInManager>();
        });

        Bind<ApplicationUserManager>().ToSelf();
    }
}

однако в HttpContextWrapper говорится, что он не содержит определения для GetOwinContext ()

Я пробовал другими способами, но я также был безуспешными.

...