How to tell use relevant registered MySession class by name

妖精的绣舞 提交于 2019-12-12 01:27:20

问题


I have project created from Boilerplate

I have MySession class that will be used from MvcControllers and WebApi Controllers.

In MySession has two derived classes:

MySessionMvc:

 public override string UserId {
  get {

   return Thread.CurrentPrincipal.Identity.GetUserId();
  }
 }

and

MySessionWebApi:

 public override string UserId {
  get {

   System.Web.HttpContext.Current.Request.Headers["UserId"];
  }
 }

I register both classes:

IocManager.RegisterIfNot<IMySession, MySessionMvc>(DependencyLifeStyle.Singleton, "MyNamespace.MySessionMvc");

IocManager.RegisterIfNot<IMySession, MySessionWebApi>(DependencyLifeStyle.Singleton, "MyNamespace.MySessionWebApi");

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.

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; }

    }
}

How can I proceed that I can correctly resolve the relevant MySession at interceptor level?


回答1:


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>();
        } 
}

That's all folks!



来源:https://stackoverflow.com/questions/53883653/how-to-tell-use-relevant-registered-mysession-class-by-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!