我正在尝试在我的.NET(4.6.1)Web API项目中集成Simple Injector(4.0.12),但无法找到一种方法来使用正确的AsyncScopedLifestyle
注册所有Web API控制器。
当我尝试将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注册为transient,但实现了IDisposable ...
有人知道如何将WebAPIController注册的生活方式设置为AsyncScoped,以便我可以注入异步范围的业务逻辑吗?
答案 0 :(得分:0)
在.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