I have a Service running on a server which listens to a Message Que. When a message is received, a new Thread is started and the message is passed to that Thread for processing.
I have defined an interface which provides access the current user for consumption in various classes used for the message processing:
public interface IUserContext {
User CurrentUser { get; }
}
This user will likely change from message to message.
My question is how do I register an implementation of IUserContext in SimpleInjector so that the correct User, contained in the incoming message, is properly returned by the CurrentUser property?
In my Asp.Net application this was accomplished by the following:
container.Register<IUserContext>(() => {
User user = null;
try {
user = HttpContext.Current?.Session[USER_CONTEXT] as IUser;
}
catch { }
return new UserContext(user);
});
I would imagine this would be accomplished using Lifetime Scoping, but I can't define that in a static class and set the User in each thread, because it could corrupt another process. This is my best guess at the implementation?
public static Func<User> UserContext { get; set; }
Then in my code in the new Thread:
using (container.BeginLifetimeScope()) {
.....
var user = GetUserContext(message);
UserContextInitializer.UserContext = () => new UserContext(user);
.....
}
Then registration would look something like this:
container.Register<IUserContext>(() => UserContextInitializer.UserContext);
Thread Safety aside, Is this the correct approach to implement this in SimpleInjector? Is there another pattern which would be more correct?
UserContext? - Robert HarveyUserContextcontains useful state. Perhaps an immutable implementation? - Robert Harvey