I want to have a class "DataSaver" that stores some data in the HTTPSession. But I also want the ability to change my mind and have the factory class create an object that instead saves to a file or database.
I want to be able to create the DataSaver object like this:
IDataSaver obj = DataSaverFact.Create();
But obviously, the data sources would require different resources depending on which get instantiated(i.e. the class that saves in session will need the current HTTPSession, and the database version will need connection string, etc...)
But I don't want to have to pass anything to the creation method.
Is that even possible?
I was thinking of using Dependancy Injection with my factory classes looking like:
public interface IDataSaverFact
{
IDataSaver Create();
}
public interface IDataSaver
{
public void Save(Object data);
}
public SessionSaver : IDataSaver
{
//PARAMETER REQUIRED SINCE SESSION ONLY AVAILABLE FROM CALLER DURING WEB REQUEST
public SessionSaver(HTTPSession session)
{
}
public void Save(Object data) {....}
}
public FileSaver : IDataSaver
{
//NO PARAMETER HERE. THIS WILL JUST SAVE TO A FILE FROM CONFIG
public FileSaver ()
{
}
public void Save(Object data) {....}
}
public DataSaverFact : IDataSaverFact
{
public IDataSaver Create()
{
* IS IT POSSIBLE/APPROPRIATE TO HOOK THIS UP VIA A DI FRAMEWORK? *
return new SessionSaver(session);
}
}
I have seen several examples, like here Is there a pattern for initializing objects created via a DI container, that seem close to what I have above, except the linked example is passing a parameter at creation time.
I don't want the creation to vary depending on the call to the factory, but I want the ability to be able to change the DataSaver at compile-time if decide to change data sources for technical reasons.
And then I would just change my factory class to be
public DataSaverFact : IDataSaverFact
{
public IDataSaver Create()
{
return new FileSaver();
}
}
*Edit, this is to be used in an MVC3 project