如何将IOptions传递给ASP.NET 5中间件服务? [英] How to pass IOptions to an ASP.NET 5 middle-ware service?

查看:63
本文介绍了如何将IOptions传递给ASP.NET 5中间件服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始使用ASP.NET 5 vNext,并且正在努力将config.json中的选项传递给WebApi控制器使用的中间件服务.

I have started playing around with ASP.NET 5 vNext and I am struggling passing the options from config.json into a middle-ware service that is used by my WebApi controller.

以下是我的中间件服务的摘录:

Here is a snippet with my middle-ware service:

public class MyService : IMyService 
{
        public MyService(IOptions<MyOptions> settings)
        {
            var o = settings.Options;
        }
}

这是我的WebApi控制器,它正在使用中间件服务:

Here is my WebApi controller that is using the middle-ware service:

public class MyController : Controller
    {
        private IMyService _myService;

        public TestController(IMyService service)
        {
            _myService = service;
        }
}

在Startup.cs中,我正在阅读以下选项:

In Startup.cs I am reading the options:

services.AddOptions();
services.Configure<MyOptions>(Configuration);

我正在努力的是如何将实例注册到IMyService,以便将其传递给控制器​​的构造函数(如何获得IOptions)?

What I am struggling with is how to register an instance to IMyService so that it would be passed to the constructor of the controller (how can I get a hold of the IOptions)?

services.AddInstance<IMyService>(new MyService(XXXXX));

如下所示,我确实尝试同时使用两者

As suggested below I did try to use both

services.AddTransient<MyService>();

services.AddSingleton<MyService>();

但是在两种情况下,我都会看到以下错误:

But in both cases I am seeing the following error:

处理请求时发生未处理的异常.

An unhandled exception occurred while processing the request.

InvalidOperationException:无法解析类型的服务 尝试激活时"MyApp.Services.IMyService" 'MyApp.Controllers.TestController'. Microsoft.Framework.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp,Type type,Type requiredBy,布尔值isDefaultParameterRequired)

InvalidOperationException: Unable to resolve service for type 'MyApp.Services.IMyService' while attempting to activate 'MyApp.Controllers.TestController'. Microsoft.Framework.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)

感谢您的帮助!

推荐答案

请勿将其注册为实例.而是根据您的要求将其添加为Scoped/Transient/Singleton,然后让Dependency Injection发挥作用;

Don't register it as an Instance. Instead just add it as Scoped/Transient/Singleton depending on your requirements and let Dependency Injection do its magic;

services.Configure<MyOptions>(Configuration.GetSection("MyOptions"));
services.AddScoped<IMyService, MyService>();

这篇关于如何将IOptions传递给ASP.NET 5中间件服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆