将传递和实例传递给以Action为参数的方法

时间:2020-05-21 13:50:30

标签: c# asp.net-core asp.net-core-identity

我有以下方法:

IdentityBuilder IServiceCollection.AddIdentityCore<User>(Action<IdentityOptions> setupAction)

我使用以下方法:

  services.AddIdentityCore<User>(x => {
    x.Password.RequiredLength = 8;
  })

这可行,但是我尝试创建具有默认值的类:

public class IdentityDefaultOptions : IdentityOptions {
  public IdentityDefaultOptions() {
    Password.RequiredLength = 8;
  }
}

并按如下所示使用它:

services.AddIdentityCore<User>(x => new IdentityOptions())

它可以编译,但不应用Password.RequiredLength。

我想念什么?

3 个答案:

答案 0 :(得分:2)

函数

name

不返回任何值, 它将更改作为参数到达的 services.AddIdentityCore<User>(x => { x.Password.RequiredLength = 8; }) 的值。

您必须获取一个x参数并更改传递的对象。

IdentityOptions

答案 1 :(得分:1)

您只是在创建一个永远不会使用的新实例。 它正在做这样的事情:

public void Test(IdentityOptions options)
{
   new IdentityOptions()
}

那根本没有道理。

相反,您必须与x对象进行交互并设置其值。等于:

public void Test(IdentityOptions options)
{
   options.Password.RequiredLength = 8;
}

您可以查看delegateanonymous methodslambda'=>' operator文档

答案 2 :(得分:0)

您为什么要尝试创建其他类型?

如果您尝试在多个位置配置IdentityOptions实例,或者使用依赖项注入对此配置进行其他决策。您可以改为配置实现IConfigureOptions<IdentityOptions>;

的服务
    public class MoreIdentityOptions : IConfigureOptions<IdentityOptions>{
        public MoreIdentityOptions(/* inject types */){}
        public void Configure(IdentityOptions options){
            x.Password.RequiredLength = 8;
        }
    }


    services.AddIdentityCore<User>();
    services.AddTransient<IConfigureOptions<IdentityOptions>, MoreIdentityOptions>();
相关问题