我正在尝试将 Simple Injector (4.0.12) 集成到我的 .NET (4.6.1) Web API 项目中,但找不到使用正确的 .NET 注册所有 Web API 控制器的方法AsyncScopedLifestyle。
当我尝试像这样将异步范围的实例DatabaseProvider注入控制器时......
public class DatabaseController : ApiController
{
private readonly IDatabaseProvider databaseProvider;
public DatabaseController(IDatabaseProvider databaseProvider)
{
this.databaseProvider = databaseProvider;
}
[HttpGet]
public bool CheckDatabaseConnection()
{
return databaseProvider.IsConnected();
}
}
...我收到SimpleInjector.ActivationException以下错误:
DatabaseProvider 注册为“Async Scoped”生活方式,但在活动(Async Scoped)范围的上下文之外请求实例。
但为什么?
这就是我注册控制器的代码的样子:
public static Container Initialize()
{
var container = new Container();
container.Options.LifestyleSelectionBehavior = new CustomLifestyleSelectionBehavior();
container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();
container.RegisterWebApiControllers(GlobalConfiguration.Configuration);
DependencyProvider.SetResolver(new SimpleInjectorDependencyProvider(container));
GlobalConfiguration.Configuration.DependencyResolver =
new SimpleInjectorWebApiDependencyResolver(container);
RegisterTypes(container);
//container.Verify();
return container;
}
public class CustomLifestyleSelectionBehavior : ILifestyleSelectionBehavior
{
public Lifestyle SelectLifestyle(Type implementationType)
{
if (implementationType.GetCustomAttribute<ApplicationScoped>(true) != null)
{
return Lifestyle.Singleton;
}
return new AsyncScopedLifestyle();
}
}
如您所见,DefaultScopedLifestyle设置为AsyncScopedLifestyle并且我也CustomLifestyleSelectionBehavior为控制器返回了相同的生活方式。
然而,所有控制器似乎都注册为Transient,因为这是container.Verify()所有控制器的输出:
异常类型:DiagnosticVerificationException
异常消息:配置无效。
报告了以下诊断警告:-[Disposable Transient Component] DatabaseController 注册为transient,但实现了IDisposable。
-[Disposable Transient Component] LoginDataController 注册为瞬态,但实现了 IDisposable。
...
有谁知道如何将 WebAPIController-registrations 的生活方式设置为 AsyncScoped 以便我可以注入异步范围的业务逻辑?