c# - 在 Unity 中使用 IOptions

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

我有一个从 ASP.Net Core(目标 4.5)和 4.5 网络应用程序引用的类库,我想共享应用程序设置。我在 4.5 端使用 Unity for DI,在 Core 端使用 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 填充该类型的实例(不确定这是否是正确的方法)

但是我在运行时遇到异常

Unable to cast object of type '.Core.Integration.Models.AppSettings' to type 'Microsoft.Extensions.Options.IOptions`1[Core.Integration.Models.AppSettings]'.

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

最佳答案

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

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

关于c# - 在 Unity 中使用 IOptions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46062583/

相关文章:

c# - 骰子程序计算不正确?

c# - ServiceCollection 不包含来自 "AddLogging"的定义

nhibernate - SimpleInjector : Injection does not work with MVC 4 ASP. NET Web API

java - Spring:如何通过 XML 将属性值注入(inject)到 bean 中?

c# - 为什么编译器找不到我的方法?

C# 相当于 std::sort 和 std::unique

C# 将子对象传递给方法以填充基类的公共(public)属性

c# - 使用通用接口(interface)和简单注入(inject)器的依赖注入(inject)

c# - 使用 TPL/async await 的递归异步调用

.net - 在不重新构建的情况下更改程序集的 list