注入创建请求范围对象的频率
本文关键字:频率 对象 范围 创建 请求 注入 | 更新日期: 2023-09-27 18:36:33
I 有以下注入配置
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
ConfigureRavenDB(kernel);
RegisterServices(kernel);
var resolver = new NinjectDependencyResolver(kernel);
GlobalConfiguration.Configuration.DependencyResolver = resolver;
return kernel;
}
和我的 RavenDB 存储配置
private static IDocumentStore ConfigureRavenDB(IKernel container)
{
var store = new DocumentStore
{
ConnectionStringName = "SpurroConnection"
};
store.Initialize();
container.Bind<IDocumentStore>().ToConstant(store).InSingletonScope();
container.Bind<IDocumentSession>().ToMethod(CreateSession).InRequestScope();
return store;
}
会话上下文管理
private static IDocumentSession CreateSession(IContext context)
{
var store = context.Kernel.Get<IDocumentStore>();
if(store != null)
{
return store.OpenSession();
}
throw new Exception("Unable to Bind the IDocument session for this user request");
}
然后我有服务类
public class ServiceA
{
private readonly IDocumentSession _documentSession;
public ServiceA(IDocumentSession documentSession)
{
_documentSession = documentSession;
}
}
public class ServiceB
{
private readonly IDocumentSession _documentSession;
public ServiceB(IDocumentSession documentSession)
{
_documentSession = documentSession;
}
}
我的问题是这个
在 Ninject 配置中创建会话的调用。它是在每个请求开始时被调用,还是在应用程序启动期间被调用一次,并且在每个请求时注入结果实例
这两个服务实现是否接收会话对象的相同实例?
每个
请求创建一次 InRequestScope 绑定对象。如果在同一请求中使用这两个服务,它们将获得相同的实例。