【问题标题】:Using IOptions with Unity在 Unity 中使用 IOptions
【发布时间】:2017-09-06 04:24:06
【问题描述】:

我有一个从 ASP.Net Core(面向 4.5)和 4.5 Web 应用程序引用的类库,我希望共享应用程序设置。我在 4.5 端使用 Unity for DI,在核心端使用 Core Bootstrapping。在核心方面,我注册了一种我的应用设置,如下所示

services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

然后我像这样引用 AppSettings

private readonly AppSettings _appSettings;
public SubmissionRepository(PricingContext dbContext, IMapper mapper, IOptions<AppSettings> appSettings)
{
     _appSettings = appSettings;
}

我想在 4.5 端注册我的服务,我可以使用 Unity 在 WebApiConfig.cs 中做到这一点

container.RegisterType<AppSettings>(new InjectionFactory(o => BuildAppSettings()));

BuildAppSettings 只是使用 ConfigurationManager 填充该类型的实例(不确定这是否是正确的做法)

但是我在运行时遇到异常

无法转换类型为“.Core.Integration.Models.AppSettings”的对象 输入 'Microsoft.Extensions.Options.IOptions`1[Core.Integration.Models.AppSettings]'。

我猜我需要以某种方式将 IOptions 实例放入我的容器中,但不确定如何执行此操作。有没有首选/更好的方法来做到这一点?

【问题讨论】:

    标签: c# .net dependency-injection unity-container


    【解决方案1】:

    如果我再用 Google 搜索 10 秒,我就会找到这个

    Options.Create(new AppSettings{
        // config reads
    });
    

    【讨论】:

    • 这是一个我使用的单例硬编码示例:Container.RegisterInstance(Options.Create(new MemoryDistributedCacheOptions()));
    猜你喜欢
    • 2019-06-12
    • 1970-01-01
    • 1970-01-01
    • 2020-08-30
    • 2020-11-27
    • 1970-01-01
    • 2021-08-22
    • 2019-05-22
    • 2019-02-14
    相关资源
    最近更新 更多