Search code examples
c#asp.net-coreasp.net-core-identity

Pass and instance to a method with Action as parameter


I have the following method:

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

Which I use as follows:

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

This works but I tried to create a class with default values:

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

And use it as follows:

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

It compiles but Password.RequiredLength is not applied.

What am I missing?


Solution

  • You are simply creating a new instance that will never be used. It is doing something like this:

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

    That makes no sense at all.

    Instead, you have to interact with the x object and set its values. It would be equals to:

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

    You might take a look at the delegate, anonymous methods and lambda and '=>' operator documentation