.NET 5 vNext Dependency Resolution with Parameters

I was able to resolve dependencies without parameterless vNext DI constructors .

But when I tried to specify a parameter for one of my dependencies, it gives a runtime error:

System.InvalidOperationException Unable to resolve service for type 'System.String' when trying to activate 'Namespace.MyService'

Constructor:

public MyService(string name)
{
    // initialize
}

      

Application:

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 constructor parameter of the Consumer class to use the type MyService

My initial registration:

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

      

I really want to use interfaces and not concrete classes for this process. How can I get this to work?

+3


source to share


3 answers


It's as simple as explicitly specifying the service type:

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

      



The compiler will usually infer the generic type of the parameter, but you can always specify generic type arguments explicitly.

+5


source


one more note, although there is little documentation on it yet, instead of taking the string in your constructor, take the IOptions class and put the string as a property of the options

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



and then if needed you can add properties to pass without changing the constructor

+1


source


There is another approach, you can add a 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>();

      

+1


source







All Articles