我有一个Web API控制器FooController
,看起来像具体类型的Web API的控制器构造
public class FooController : ApiController
{
private readonly IDictionary<string, string> messageDictionary;
private readonly TimeSpan timeout;
public FooController(IDictionary<string, string> messageDictionary, TimeSpan timeout)
{
// set fields
}
public async Task<IHttpActionResult> Post([FromBody] string message)
{
try
{
using (var tokenSource = new CancellationTokenSource(timeout))
{
CancellationToken token = tokenSource.Token;
// call some api
token.ThrowIfCancellationRequested();
// do some other stuff
token.ThrowIfCancellationRequested();
return Ok();
}
}
catch
{
// LogException
return InternalServerError();
}
}
}
当我尝试使用该控制器,我得到,指出没有默认构造函数的错误,这是好,那很明显。
我从web.config
文件中使用自定义配置部分,它由Global.asax
文件看起来像这样在阅读了messageDictionary
值
private IDictionary<string, string> messageDictionary;
private TimeSpan controllerTimeout;
// ...
void Application_Start(object sender, EventArgs e)
{
GlobalConfiguration.Configure(WebApiConfig.Register);
messageDictionary = BuildMessageDictionaryFromConfig();
controllerTimeout = GetControllerTimeoutFromConfig();
}
我的目标是让控制器不必担心关于从配置中读取东西,或者从Global
拉入messageDictionary
。
我看着为了打造控制器我需要有扩展DefaultControllerFactory
,但对于我的新控制器工厂构造从来没有所谓,尽管像
ControllerBuilder.Current.SetControllerFactory(new FooControllerFactory());
或
ControllerBuilder.Current.SetControllerFactory(typeof(FooControllerFactory));
在
Global#Application_Start
对其进行注册
我考虑制作一个新的IMessageDictionary
接口,以便我可以使用DI(因为我在不同控制器中有不同的IDictionary<string, string>
字段包含不同的数据),但t帽子并没有解决构造函数中参数timeout
的问题。
我该如何解决这个问题?
您可以注入一个服务接口,为您的控制器执行此项工作。我不确定这是否真的会改善您的设计。 – Noppey
注入一个'ITimeoutProvider'并为其创建一些简单的实现并将其注册到DI服务中。如果你不使用DI,那么考虑一个像AutoFac这样的框架。 – Igor