我刚刚在我的 ASP.NET Web 窗体应用程序中发现了一个错误,其中请求范围的服务 ( ServiceA
) 被注入到单例服务 ( ServiceB
) 中,其不利影响是使用单例的东西正在从另一个长期失效的请求中获取内容。
我真的很想ServiceA
成为请求范围,因为它允许我在本地缓存检索到的与用户会话相关的数据,但显然我不应该将它注入到单例服务中(不知道为什么 NInject 在构建图表时没有抛出异常但这是一个单独的问题)。
我的解决方案是创建一个优化程度较低(即非缓存)的单例版本,ServiceA
并调整现有的请求范围版本以缓存结果,但从单例版本(本身是一个依赖项)中获取实际数据。两个版本都将实现接口IServiceA
。
我遇到的问题是,我想让 NInject在注入单例SingletonServiceA
时使用类,并在注入请求范围的服务时使用类。IServiceA
RequestScopedServiceA
IServiceA
有没有办法做到这一点,以便不需要将当前请求的所有服务IServiceA
更改为显式请求中间接口(ISingletonServiceA
或IRequestScopedServiceA
)?
我尝试了以下方法:
public interface IServiceA
{
// Actual interface defined here
}
public interface IRequestScopedServiceA : IServiceA
{
}
public interface ISingletonServiceA : IServiceA
{
}
public class RequestScopedServiceA : IRequestScopedServiceA
{
private readonly ISingletonServiceA _serv;
public RequestScopedServiceA(ISingletonServiceA serv)
{
_serv = serv ?? throw..;
}
// Get and cache data here
}
public class SingletonServiceA : ISingletonServiceA
{
// Always get data from source
}
NInject 模块需要做这样的事情:
// If a service asks for a specific scoped version then these can be used:
Bind<IRequestScopeServiceA>().To<RequestScopeServiceA>().InRequestScope();
Bind<ISingletonServiceA>().To<SingletonServiceA>().InRequestScope();
// But ideally I would like NInject to select the right implementation based on
// the outer service's scope e.g.
Bind<IServiceA>()
.WhenSingleton<RequestScopeServiceA>()
.WhenRequestScope<SingletonServiceA>();
有没有办法做到这一点?