Dependency Injection and user specific data
I have application that uses ORM (Nhibernate but it's not the case).
To create NH Session we need to pass somewhere: username, database name, etc. So I have implemented:
public interface ISettingsManager
{
Settings MySettings {get;set;}
}
public class Settings
{
public string DbUser{get;set;}
public string DbAddress {get;set;}
public string DbPassword{get;set;}
//...
}
public class Se开发者_如何学GossionProvider
{
[Inject]
public ISettingsManager MySettings {get;set;}
public Session CreateSession
{
//Create Session object using settings passed do MySettings via IoC.
}
}
public static Main()
{
// very beggining of my application, bootstrap the DI container
Bind<ISettingsManager>().To<SettingsManagerImpl>();
// Application run
}
All my NHibernate Session Providers have the ISettingsManager
injected to it via DI (Ninject) so I can simple use it. It works like a harm, but now I need to support many users in my application and the problem goes into the scene. I cant bind my ISettingsManager when applications starts, becauese I dont now wchich user will be logged in.
So the question is, how to implement passing current logged user settings in the best way, without using Service Location?
Assuming I understood the problem correctly, something like the singleton pattern could help (see http://en.wikipedia.org/wiki/Singleton_pattern).
One singleton would store the information and give it when requested. Other components would need to know only how to access the singleton, not anything more specific.
For getting individual user settings out the singleton, a dictionary type of data structure that maps keys (like user id) to values could be good.
I would use a separate DB for all authentications, then pull out the user-specific DB settings from that DB.
Using the user specific setting retrieved, I would create the class you want to inject into your ORM's connection process and inject it using either constructor or property injection.
精彩评论