[英]Using .NET Core DI with runtime parameters?
I've created a simple Echo
class (for cimplicity) with IEcho
Interface : 我已经使用IEcho
接口创建了一个简单的Echo
类(出于简洁):
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. 基本上,它将返回与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. "Hey"
值是在编译时提供的。
How can I send the "Hey"
value in runtime rather compile time ? 如何在运行时而不是编译时发送"Hey"
值?
Create an IEchoFactory
and inject it. 创建一个IEchoFactory
并注入它。
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.