SteinTech
SteinTech

Reputation: 4068

How to create an IOptions<T> from a custom instance of T (not via DI)

I would like to pass a value to an IOptions<T> parameter.

I can only find examples of using IOptions<T> with configuration, but I need to define a custom value when invoking a method.

Upvotes: 10

Views: 6715

Answers (2)

Marcell Toth
Marcell Toth

Reputation: 3688

I am assuming that you are asking how to create a custom IOptions<TOptionClass> value where you specify the instance of T to be used. Here is how you can do that:

Let's assume you have a class called IdentityOptions as in your example.

First create an instance of it:

var optionsInstance = new IdentityOptions();
// ... set properties on it as needed

Then convert it into an Option-container:

IOptions<IdentityOptions> optionParameter = Options.Create(optionsInstance);

See MSDN.

Update: I was a few seconds slower than the OP's own solution. Let me add a possible extension-method solution so this answer still has some added value (not tested):

public static IOptions<TOptions> AsIOption<TOptions>(this TOptions optionInstance) where TOptions : class, new()
{
    return Microsoft.Extensions.Options.Options.Create(optionInstance);
}

Which then you can use as optionInstance.AsIOption(). I'm not sure if it's worth the effort (I don't like to pollute the Object class if not necessary), but certainly possible, and might get useful if you use this technique at many different places.

Upvotes: 16

SteinTech
SteinTech

Reputation: 4068

My solution:

public LCSignInManager(UserManager<Profile> userManager, IdentityDbContext db, IHttpContextAccessor contextAccessor, IUserClaimsPrincipalFactory<Profile> claimsFactory, IOptions<IdentityOptions> optionsAccessor = null) : base(userManager, contextAccessor, claimsFactory, optionsAccessor, new LoggerFactory().CreateLogger<LCSignInManager>(), (IAuthenticationSchemeProvider)new AuthenticationSchemeProvider(GetOption()).GetDefaultAuthenticateSchemeAsync().Result)
{
    _userManager = userManager;
    this.DbContext = db;
}

private static IOptions<AuthenticationOptions> GetOption()
{
    var settings = new AuthenticationOptions
        {

        };

    IOptions<AuthenticationOptions> result = Microsoft.Extensions.Options.Options.Create(settings);

    return result;
}

Upvotes: 0

Related Questions