简体   繁体   中英

Using .NET Core DI with runtime parameters?

I've created a simple Echo class (for cimplicity) with IEcho Interface :

 public interface IEcho
    {
        string Value { get; set; }
    }

    public class Echo : IEcho
    {
        public Echo(string s  )
        {
            Value = s;
        }

        public string Value { get; set; }
    }

Basically , it will return the same value as provided in ctor.

I'm registering it as :

public IEcho Echo { get; }

private void ConfigureServices(IServiceCollection serviceCollection)
    {
        serviceCollection.AddTransient<IEcho >(a=>new Echo("Hey"));
    }

And indeed it works :

在此处输入图片说明

Question:

The "Hey" value was supplied in compile time.

How can I send the "Hey" value in runtime rather compile time ?

Create an IEchoFactory and inject it.

interface IEchoFactory
{
    IEcho GetEcho( string text );
}

class EchoFactory : IEchoFactory
{
    public IEcho GetEcho(string text)
    {
        return new Echo(text);
    }
}


serviceCollection.AddTransient<IEchoFactory, EchoFactory>();

And in the code that received the injection, instead of

var t = _echo.Value;  //Assuming _echo is populated via injection

use

var e = _echoFactory.GetEcho("String determined at runtime"); 
var t = e.Value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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