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

Pass and instance to a method with Action as parameter

我有以下方法:

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

我使用如下:

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

这行得通,但我试图用默认值创建 class:

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

并按如下方式使用:

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

它编译但 Password.RequiredLength 没有应用。

我错过了什么?

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

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

这完全没有意义。

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

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

您可以查看 delegate, anonymous methods and lambda and '=>' operator 文档

函数

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

return 没有任何价值, 它更改作为参数到达的 x 的值。

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

public void DefaultIdentityOptions(IdentityOptions x)
{
  x.Password.RequiredLength = 8;    
}

您为什么要尝试创建不同的类型?

如果您尝试在多个地方配置 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>();