Search code examples
c#castle-windsorioc-containeraspnetboilerplate

How to tell use relevant registered MySession class by name


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?


Solution

  • 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!