我真的很喜欢这种模式,我可以通过选项类配置服务而无需创建它,但我找不到如何编写扩展方法的示例,该方法允许我使用相同的模式,例如下面的一个用于注册 DbContext。
services.AddDbContext<MyDbContext>(options => options.EnableDetailedErrors());
我可以看到方法签名使用了一个操作方法,但我似乎无法在 GitHub 中找到 ASP.NET Core 的扩展类,它向我展示了如何使用该类型的选项构建器模式编写扩展方法。
例如,采用以下服务代码。我如何编写扩展方法,以便我可以在服务注册期间配置选项。
public void ConfigureServices(IServiceCollection services)
{
services.AddMyService(options => options.SomeSetting = true);
}
public interface IMyService
{
void DoSomething();
}
public class MyService : IMyService
{
private readonly MyServiceOptions _options;
public MyService(IOptions<MyServiceOptions> options)
{
_options = options.Value;
}
public void DoSomething()
{
Console.WriteLine(_options.SomeSetting);
}
}
public static class MyServiceExtensions
{
// How would I write this extension method so that I could configure it with options overload
public static IServiceCollection AddMyService(this IServiceCollection services, Action<MyServiceOptions> configure)
{
services.AddSingleton<IMyService, MyService>();
return services;
}
}
最佳答案
ASP.NET Core provides this mechanism with the IConfigureOptions interface. You implement this interface in a configuration class and use it to configure the IOptions object in any way you need.
很简单:
public class MyServiceConfiguration : IConfigureOptions<MyServiceOptions>
{
private MyServiceOptions _options;
public MyServiceConfiguration(IOptions<MyServiceOptions> options)
{
_options = options.Value;
}
public void Configure(MyServiceOptions options)
{
options.SomeSetting = _options.SomeSetting;
options.SomeOtherSetting = _options.SomeOtherSetting;
}
}
All that remains is to register this implementation in the DI container.:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<MyServiceOptions>(options => options.SomeOtherSetting = true);
services.AddSingleton<IMyService, MyService>();
}
通过此配置,当 IOptions 注入(inject)到您的服务中时,MyServiceOptions 对象将由 ConfigureMyServiceOptions 类进行配置。
Be careful!
The ConfigureMyServiceOptions object is registered as a singleton, so it will capture any injected services of scoped or transient lifetimes.
关于asp.net-core - 如何编写一个扩展方法,允许您在不创建选项实例的情况下设置选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58141089/