1

I need an instance of a class to be created only once per user session. How do I register such a class with TinyIoC? I'm using NancyFx.

ulu
  • 5,872
  • 4
  • 42
  • 51
  • Are you talking about per web request? – tom redfern Jan 29 '16 at 16:27
  • No, per user session. Meaning that it should be the same instance for all request made by a user as long as her Session object stays alive. Not too hard to implement, but I thought it's done by somebody else already. – ulu Jan 29 '16 at 17:44
  • 1
    have you looked at https://github.com/romis2012/Nancy.Sessions ? – tom redfern Jan 30 '16 at 09:18
  • No, thanks for the pointer! It doesn't do what I need, but I could use it for my own implementation. – ulu Jan 30 '16 at 17:26
  • If you could get hold of your static container in the session start method you could do you per session registration there perhaps – tom redfern Jan 30 '16 at 17:31

1 Answers1

2

I ended up writing the following code:

public static class ContainerExtensions {
    public static TinyIoCContainer.RegisterOptions SessionScoped<TRegisterType>(this TinyIoCContainer container, NancyContext context, Func<TRegisterType> factory) where TRegisterType : class
    {
        return container.Register<TRegisterType>((ctx, overloads) =>
        {
            var key = typeof(TRegisterType).FullName;
            var instance = context.Request.Session[key] as TRegisterType;
            if (instance == null) {
                instance = factory();
                context.Request.Session[key] = instance;
            }
            return instance;
        });
    }
}

I used the Nancy.Session.InProc NuGet.

ulu
  • 5,872
  • 4
  • 42
  • 51