如何通过名称告诉使用相关的已注册MySession类 [英] How to tell use relevant registered MySession class by name
问题描述
我有一个从样板
我有MySession类,该类将在MvcControllers和WebApi Controllers中使用.
I have MySession class that will be used from MvcControllers and WebApi Controllers.
在MySession中有两个派生类:
In MySession has two derived classes:
MySessionMvc:
MySessionMvc:
public override string UserId {
get {
return Thread.CurrentPrincipal.Identity.GetUserId();
}
}
和
MySessionWebApi:
MySessionWebApi:
public override string UserId {
get {
System.Web.HttpContext.Current.Request.Headers["UserId"];
}
}
我注册了两个课程:
IocManager.RegisterIfNot<IMySession, MySessionMvc>(DependencyLifeStyle.Singleton, "MyNamespace.MySessionMvc");
IocManager.RegisterIfNot<IMySession, MySessionWebApi>(DependencyLifeStyle.Singleton, "MyNamespace.MySessionWebApi");
现在是该告诉哪个MySession派生类用于相关控制器的时候了.
Now it is time to tell the which MySession derived class will be used for relevant controller.
一个可怕"的解决方案,将容器注入每个控制器并使用它
现在,我可以轻松将其注入到我的控制器中了
A "horrible" solution, inject container to each controller and use it
I see now I can easily inject it to my controller
protected MyBaseController(IWindsorContainer container)
{
MySession = container.Resolve<IMySession> "MyNamespace.MySessionWebApi");
}
在控制器级别,我实现了我的目标.
And at controller level I achieve my goal.
另一方面,我需要告诉Auditing拦截器说相同的依赖项解析.该拦截器从MySession获取UserId信息.
On the other hand I need to tell Auditing interceptor tell same dependency resolve. This interceptor takes UserId info from MySession.
namespace My.Auditing
{
internal class AuditingInterceptor : IInterceptor
{
public IMySession MySession { get; set; }
}
}
我如何才能在拦截器级别正确解析相关的MySession?
How can I proceed that I can correctly resolve the relevant MySession at interceptor level?
推荐答案
IocManager.IocContainer.Register(
Component.For<MySessionWebApi>().LifestylePerWebRequest(), Component.For<MySessionMvc>().LifestylePerWebRequest(),
Component.For<IMySession>().UsingFactoryMethod((k, c) => this.MySessionFactory(k)).LifestylePerWebRequest().IsDefault());
private IMySession MySessionFactory(IKernel kernel)
{
if (System.Web.HttpContext.Current.Request == null)
{
return (IMySession)kernel.Resolve<MySessionMvc>();
}
if (System.Web.HttpContext.Current.Request.Path.Contains("/api/"))
{
return (IMySession)kernel.Resolve<MySessionWebApi>();
}
else
{
return (IMySession)kernel.Resolve<MySessionMvc>();
}
}
这就是所有人!
这篇关于如何通过名称告诉使用相关的已注册MySession类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!