0

我的 APS.NET 服务有一个配置,它通过把手解析它的一些配置字符串。它是一个通过AddSingleton使用添加的单例GetSection,如下所示:

    services.AddSingleton<Configuration.IConfiguration(Configuration.GetSection("Configuration")
            .Get<Rest_Api.Configuration.Configuration>());

现在我是 DI 的新手并尝试一些原则。HandlebarsHandle所以配置需要一个我想要注入的所谓的。

处理程序的代码是:

public interface IHandlebarsHandler 
{
    string Resolve(string contentTemplate, dynamic context);
}

public class HandlebarsHandler : IHandlebarsHandler
{
    public string Resolve(string contentTemplate, dynamic context)
    {
        var template = Handlebars.Compile(contentTemplate);

        // resolve bindings with dynamic context
        var result = template(context);

        return result;
    }
}

配置代码为:

public interface IConfiguration 
{
    string StudentsJsonPath { get; set; }
    string EmployeesJsonPath { get; set; }
    string IdmsRestService { get; set; }
    string AddressRoute { get; set; }
    string Get(string propertyName, dynamic context = null);
    bool Contains(string propertyName);
    List<string> GetPropertyNames();
    void SetHandlebars(IHandlebarsHandler handler);
}

public class Configuration : IConfiguration
{
    private static NLog.Logger Log = LogManager.GetCurrentClassLogger();

    public string StudentsJsonPath { get; set; }
    public string EmployeesJsonPath { get; set; }
    public string IdmsRestService { get; set; }
    public string AddressRoute { get; set; }

    private PropertyInfo _actual;

    private IHandlebarsHandler _handler;

    public bool Contains(string propertyName)
    {
        return (_actual = typeof(Configuration).GetProperty(propertyName)) != null;
    }

    public List<string> GetPropertyNames() 
        => typeof(Configuration).GetProperties().Select(p => p.Name).ToList();

    public void SetHandlebars(IHandlebarsHandler handler) => _handler = handler;

    public string Get(string propertyName, dynamic context = null)
    {
        var propertyValue = 
            _actual?.Name == propertyName ? _actual.GetValue(this) : typeof(Configuration).GetProperty(propertyName).GetValue(this);

        if (_handler == null)
        {
            Log.Warn("HandlerbarsHandler was null. Default will be implementation of RestApi. If you are running Tests you may want to inject an other Handler");
            _handler = new HandlebarsHandler();
        }

        return _handler.Resolve(propertyValue.ToString(), context);
    }
}

在 StartUp.cs 中,我将 Handler 添加为 Scope,将 Configuration 添加为 Singleton:

        services.AddScoped<IHandlebarsHandler, HandlebarsHandler>();
        services.AddSingleton<Configuration.IConfiguration>(Configuration.GetSection("Configuration").Get<Rest_Api.Configuration.Configuration>());

如您所见,每次我需要一个“已解决”字段时,我都必须在配置中使用以下命令设置处理程序:SetHandlebars

但我认为有更好的方法将处理程序注入配置。

有人可以解释一下吗?

4

0 回答 0