将数据传递给 startup.cs [英] Pass data to startup.cs
问题描述
如何将数据传递到 startup.cs 中?
How do you pass data into startup.cs ?
这是使用 WebHostBuilder
和 TestServer
我需要根据测试夹具传递不同的数据.所以不想从配置文件中拉进来,例如
I need to pass different data depending on the Test Fixture. So dont want to pull it in from a config file, for example
数据将提供给startup.cs中注册的中间件
The data will be supplied to a registered Middleware in startup.cs
文档似乎表明这应该有效:
Docs seem to suggest this should work:
var configBuilder = new ConfigurationBuilder()
.AddInMemoryCollection(new[]
{
new KeyValuePair<string, string>("key", "value"),
});
var configuration = configBuilder.Build();
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseConfiguration(configuration) // config added here
.UseStartup<Startup>()
.Build();
host.Run();
但是当我检查 startup.cs 中的 Configuration 对象时,密钥不存在.并且只有在 startup.cs 中定义的提供程序可用.
but when I inspect the Configuration object in startup.cs, the key is not present. And only the providers defined in startup.cs are available.
我目前正尝试在 program.cs 中执行此操作以测试概念,然后将转向集成测试
I am trying to do this in program.cs at the moment to test the concept, then will move to integration tests later
知道我做错了什么吗?
是否有更好的方法将数据传递到启动中?
Is there a better way to pass data into startup?
推荐答案
将数据发送到 Startup
的一种方法是在 Main
中注册服务.WebHostBuilder
有 ConfigureServices
方法,可以像在 Startup
类中实现的 ConfigureServices
方法一样使用.
One way to send data into the Startup
would be to register a service in Main
. WebHostBuilder
has ConfigureServices
method which can be used just like the ConfigureServices
method you can implement in the Startup
class.
例如,您可以使用静态变量创建一个类(这不是最好的主意,但有效)
For example you can make a class with static variables (not the best idea but works)
public class DataContainer
{
public static string Test;
}
然后设置其值并将其添加为单例服务
Then set its values and add it as a singleton service
DataContainer.Test = "testing";
var host = new WebHostBuilder()
.ConfigureServices(s => { s.AddSingleton(typeof(DataContainer)); })
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseConfiguration(configuration) // config added here
.UseStartup<Startup>()
.Build();
在此之后,您的Startup
可以使用常规注入方式来获取此
After this your Startup
can just use the regular injection way to get this
public Startup(IHostingEnvironment env, DataContainer data)
{
// data.Test is available here and has the value that has been set in Main
}
注入当然适用于此后的任何类和方法,而不仅仅是构造函数.
The injection of course works in any class and method after this, not just the constructor.
我不确定这是否比实际创建一个具有静态值的类本身更好,但如果该类有时需要更改,则可以将其制成接口和其他常见的注入好处.
I'm not sure if this is any better than to actually create a class with static values by itself but if the class needs to be changed sometimes it can be made into an interface and the other usual injection benefits.
这篇关于将数据传递给 startup.cs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!