I have a series of Factory objects I wish to expose trough a "root" utility (object). This root utility is in-and-of itself...a factory. As a utility object, I wish to implement it as a static class. However, isn't possible using my current design...as you cannot implement static members in an interface.
So...
MY QUESTION IS: How can I alter the classes below to get the static factory affect above?
THE CODE LOOKS LIKE:
public interface IFactory
{
I Create<I>();
IFactoryTransform Transformer { get; }
IFactoryDataAccess DataAccessor { get; }
IFactoryValidator Validator { get; }
}
public static class Factory : IFactory
{
static Factory()
{
Transformer = new FactoryTransform();
DataAccessor = new FactoryDataAccess();
Validator = new FactoryValidator();
}
public I Create<I>()
{
var model = typeof(I);
// Activation code will go here...
throw new NotSupportedException("Type " + model.FullName + " is not supported.");
}
public IFactoryDataAccess DataAccessor { get; private set; }
public IFactoryTransform Transformer { get; private set; }
public IFactoryValidator Validator { get; private set; }
}
You can move your static keyword from Factory
class to one level up. For example you can have a static class Utils
, where you have a singleton property MyFactory
.
public static class Utils
{
public static IFactory MyFactory {get; private set}
static Utils()
{
MyFactory = new Factory();
}
}
//usage
var myInterface = Utils.MyFactory.Create<IMyInterfrace>()
That said, I would probably use DI instead of the factories and IoC container to manage lifetime of the objects.