我的 Web API 正在为一个控制器使用其他项目。服务工作正常。但是我正在努力将连接字符串从主 Web API 项目注入到外部项目中的控制器中。
如何实现这一点?
public class MyExternalController : Controller
{
private string _connStr;
public MyExternalController(string connStr)
{
_connStr = connStr;
}
// actions here
}
正如其他人在评论中所说,对于像控制器这样的东西,你应该注入一些具体的东西,比如DbContext
,而不是连接字符串。但是,为了将来参考,您在此处的问题是注入字符串。无法在 DI 容器中注册某些内容来满足这样的依赖项。相反,您应该注入配置或强类型配置类。
注入IConfigurationRoot
有点反模式,但对于连接字符串之类的东西,这很好:
public MyExternalController(IConfigurationRoot config)
{
_connStr = config.GetConnectionString("MyConnectionString");
}
但是,对于其他所有内容,您应该使用强类型配置类。
public class FooConfig
{
public string Bar { get; set; }
}
然后,在ConfigureServices
:
services.Configure<FooConfig>(Configuration.GetSection("Foo"));
当然,这将对应于一些配置,例如:
{
"Foo": {
"Bar": "Baz"
}
}
然后,在控制器中,例如:
public MyExternalController(IOptionsSnapshot<FooConfig> fooConfig)
{
_fooConfig = fooConfig.Value;
}