Created
July 10, 2019 16:39
-
-
Save leniel/75217b616f036ff514e93440f30fb3eb to your computer and use it in GitHub Desktop.
AutoFact to Ninject ConfigurationSetupExtensions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using Ninject; | |
using Microsoft.Extensions.Configuration; | |
using Microsoft.Extensions.Options; | |
namespace MyProject.Extensions | |
{ | |
public static class ConfigurationSetupExtensions | |
{ | |
// Ninject version of: | |
// https://github.com/aspnet/Options/blob/rel/1.1.1/src/Microsoft.Extensions.Options/OptionsServiceCollectionExtensions.cs#L20 | |
public static void RegisterOptions(this StandardKernel container) | |
{ | |
container.Bind(typeof(OptionsManager<>)) | |
.To(typeof(IOptions<>)) | |
.InSingletonScope(); | |
container.Bind(typeof(OptionsMonitor<>)) | |
.To(typeof(IOptionsMonitor<>)) | |
.InSingletonScope(); | |
container.Bind(typeof(IOptionsSnapshot<>)) | |
.To(typeof(IOptionsSnapshot<>)) | |
.InSingletonScope(); | |
} | |
public static void Configure<TOptions>(this StandardKernel container, Action<TOptions> configureOptions) | |
where TOptions : class | |
{ | |
if (container == null) | |
{ | |
throw new ArgumentNullException(nameof(container)); | |
} | |
if (configureOptions == null) | |
{ | |
throw new ArgumentNullException(nameof(configureOptions)); | |
} | |
var configOptions = new ConfigureOptions<TOptions>(configureOptions); | |
container.Bind<ConfigureOptions<TOptions>>().ToConstant(configOptions).InSingletonScope(); | |
} | |
// Ninject version of: | |
// https://github.com/aspnet/Options/blob/rel/1.1.1/src/Microsoft.Extensions.Options.ConfigurationExtensions/OptionsConfigurationServiceCollectionExtensions.cs#L22 | |
public static void RegisterConfigurationOptions<TOptions>(this StandardKernel container, IConfiguration config) | |
where TOptions : class | |
{ | |
if (container == null) | |
{ | |
throw new ArgumentNullException(nameof(container)); | |
} | |
if (config == null) | |
{ | |
throw new ArgumentNullException(nameof(config)); | |
} | |
var ccts = new ConfigurationChangeTokenSource<TOptions>(config); | |
container.Bind<IOptionsChangeTokenSource<TOptions>>().ToConstant(ccts).InSingletonScope(); | |
var cfco = new ConfigureFromConfigurationOptions<TOptions>(config); | |
container.Bind<IConfigureOptions<TOptions>>().ToConstant(cfco).InSingletonScope(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment