简体   繁体   English

.NET 5 vNext使用参数解析依赖项

[英].NET 5 vNext Resolving dependencies with parameters

I have been able to resolve dependencies with parameterless constructors using vNext DI . 我已经能够使用vNext DI解决无参数构造函数的依赖关系。

But when I tried to specify a parameter for one of my dependencies, it gives runtime error: 但是当我尝试为其中一个依赖项指定参数时,它会给出运行时错误:

System.InvalidOperationException Unable to resolve service for type 'System.String' while attempting to activate 'Namespace.MyService' System.InvalidOperationException尝试激活“Namespace.MyService”时无法解析类型“System.String”的服务

Constructor: 构造函数:

public MyService(string name)
{
    // initialize
}

Usage: 用法:

private readonly IMyService _myService;
public Consumer(IMyService myService)
{
        // initialize
        _myService = myService;
}

I updated this dependency registration by adding: 我通过添加:

services.AddInstance(new MyService("Hello"));

It only works if I update the Consumer class constructor parameter to use type MyService 它仅在我更新Consumer类构造函数参数以使用类型MyService时才有效

My initial registration was: 我最初的注册是:

services.AddTransient<IMyService, MyService>(); // Todo: configure constructor injection

I really want to use the interfaces not the concrete classes for this process. 我真的想使用接口而不是这个过程的具体类。 How can I get this to work? 我怎样才能让它发挥作用?

It's as simple as explicitly specifying the type of the service: 它就像显式指定服务类型一样简单:

services.AddInstance<IMyService>(new MyService("Hello"));

The compiler would normally infer the generic parameter type, but you can always explicitly specify generic type arguments. 编译器通常会推断泛型参数类型,但您始终可以显式指定泛型类型参数。

another thing to consider though there is not much documentation on it yet, is instead of taking a string in your constructor take an IOptions class and put the string as a property of the options 另外要考虑的事情虽然还没有太多的文档,但是不是在构造函数中使用字符串,而是使用IOptions类并将字符串作为选项的属性

http://shazwazza.com/post/using-aspnet5-optionsmodel/ http://shazwazza.com/post/using-aspnet5-optionsmodel/

then later if needed you can add properties to pass in without changing the constructor 然后,如果需要,您可以添加要传入的属性而不更改构造函数

There is another approach, you can add config class: 还有另一种方法,你可以添加配置类:

public class MyServiceConfig
{
    public MyServiceConfig(string name)
    {
        // initialize
    }
}

public class MyService
{
    public MyService(MyServiceConfig myServiceConfig)
    {
        // initialize
    }
}

services.AddInstance(new MyServiceConfig("Hello"));
services.AddTransient<IMyService, MyService>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM