Skip to content

robersonliou/NetCoreOptionSample

Repository files navigation

NetCoreOptionSample

It's a sample for directly injecting TOption without depending on IOptions in ASP.NET Core MVC 3.1 project.

What's the problems of IOptions<T> ?

IOptions is the official approach for inject config model with options pattern.

Assumed that we have a option model called AuthOptions. To use IOpstions, You should configure the option model in Startup.cs.

Starup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<AuthConfig>(Configuration.GetSection("MyAuth"));
}

Then inject IOptions<AuthConfig> into constructor. HomeController.cs

public class HomeController : Controller
{
    private AuthConfig _authConfig;

    public HomeController(IOptions<AuthConfig> config)
    {
        _authConfig = config.Value;
    }
    //...
}

But there is a few cons of IOptions:

  • Can not directly inject the config model without depending on IOptions.
  • Inappropriate responsibility for the lifecycle of config injection ( By default is singleton ).

To use official approach with IOptions, you can check official link here.

Using Extension method.

To solve the problems above, I wrote the extension methods with combining built-in DI component and Bind(). So that I could directly inject my option model and setup the lifycycle in the Startup.cs.

Starup.cs/ConfigureServices

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingletonConfig<AuthConfig>(Configuration.GetSection("MyAuth"));
    //services.AddScopedConfig<AuthConfig>(Configuration.GetSection("MyAuth"));
    //services.AddTransientConfig<AuthConfig>(Configuration.GetSection("MyAuth"));

    //services.AddConfig<AuthConfig>(Configuration.GetSection("MyAuth"), ServiceLifetime.Singleton);
    //services.AddConfig<AuthConfig>(Configuration.GetSection("MyAuth"), ServiceLifetime.Scoped);
    //services.AddConfig<AuthConfig>(Configuration.GetSection("MyAuth"), ServiceLifetime.Transient);

    //...
}

To learn more implement details, please check Extensions/ServiceCollectionExtensions.cs file.

Finally, Give me a ⭐️ if it helps.

About

It's a sample for directly inject TOption without depending on IOptions.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published