我正在尝试将 Simple Injector (4.0.12) 集成到我的 .NET (4.6.1) Web API 项目中,但无法找到一种方法来使用正确的 AsyncScopedLifestyle
注册所有 Web API Controller .
当我尝试像这样将 DatabaseProvider
的异步作用域实例注入(inject) Controller 时...
public class DatabaseController : ApiController
{
private readonly IDatabaseProvider databaseProvider;
public DatabaseController(IDatabaseProvider databaseProvider)
{
this.databaseProvider = databaseProvider;
}
[HttpGet]
public bool CheckDatabaseConnection()
{
return databaseProvider.IsConnected();
}
}
...我收到一个 SimpleInjector.ActivationException
错误如下:
The DatabaseProvider is registered as 'Async Scoped' lifestyle, but the instance is requested outside the context of an active (Async Scoped) scope.
但为什么呢?
这是我注册 Controller 的代码:
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
为 Controller 返回相同的生活方式。
但是所有 Controller 似乎都被注册为Transient,因为这是所有 Controller 的container.Verify()
的输出:
Exception Type: DiagnosticVerificationException
Exception Message: The configuration is invalid.
The following diagnostic warnings were reported:-[Disposable Transient Component] DatabaseController is registered as transient, but implements IDisposable.
-[Disposable Transient Component] LoginDataController is registered as transient, but implements IDisposable.
...
有人知道如何将 WebAPIController 注册的生活方式设置为 AsyncScoped 以便我可以注入(inject)异步范围的业务逻辑吗?
最佳答案
在 .NET Core 中添加:
// Sets up the basic configuration that for integrating Simple Injector with
// ASP.NET Core by setting the DefaultScopedLifestyle, and setting up auto
// cross wiring.
services.AddSimpleInjector(_container, options =>
{
// AddAspNetCore() wraps web requests in a Simple Injector scope and
// allows request-scoped framework services to be resolved.
options.AddAspNetCore()
.AddControllerActivation();
});
通过https://simpleinjector.readthedocs.io/en/latest/aspnetintegration.html
关于c# - 简易喷油器 : cannot register Web API controllers with AsyncScopedLifestyle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47884621/