Rém*_*émy 12 c# dependency-injection asp.net-core-mvc .net-core asp.net-core
我在 appSettings.json 文件中有一个带有多个参数的 asp.net 核心 Web 应用程序。
我不想IOptions<MyObject>在构造函数中提供服务。
我想在构造函数中使用 MyObject。所以我找到了以下文章:https : //weblog.west-wind.com/posts/2017/dec/12/easy-configuration-binding-in-aspnet-core-revisited,这很有趣。
但我想更进一步。我想创建一个扩展方法来生成注入。
这是我想做的事情:
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Common.WebTools.Extensions
{
public static class IServiceCollectionExtensions
{
public static IServiceCollection AddSingletonConfigurationObject<T>(this IServiceCollection services,
IConfiguration configuration,
string appSettingsKey) where T:new()
{
var obj2 = new T();
configuration.Bind(appSettingsKey, obj);
services.AddSingleton(obj2); //compilation failed
return services;
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后在我的 ConfigureServices 方法中我可以调用
services.AddSingletonConfigurationObject<Common.Tools.Configuration.GoogleAnalyticsConfiguration>(Configuration, "GoogleAnalytics");
Run Code Online (Sandbox Code Playgroud)
但我在这一行有一个编译错误:
services.AddSingleton(obj2);
Run Code Online (Sandbox Code Playgroud)
有人知道我该如何纠正错误吗?
Ton*_*Ngo 28
您可以使用 services.AddScoped 在范围请求中仅使用 1 个实例。因此,与 AddTransient 相比,总体上有所改进
services.AddScoped(typeof(IGenericRepository<>), typeof(GenericRepository<>));
Run Code Online (Sandbox Code Playgroud)
所以我的界面和类看起来像这样
public interface IGenericRepository<T> where T : class
Run Code Online (Sandbox Code Playgroud)
public class GenericRepository<T> : IGenericRepository<T> where T : class
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15805 次 |
| 最近记录: |