Well I guess you could use an IoC container, since several of this also offer an ObjectFactory, ie you tell the IoC how to make a new instance of type T and then you just ask the IoC to give you an instance of it.
However if you dont want to get an IoC, you could make yourself a little factory class
public MagicFactory
{
T arg1, T2 arg2, T3 arg3,.., TN argN;
public MagicFactory(T1 a1,..., TN aN)
{
this.arg1=a1;
...
this.argN = an;
}
public Thing GimmeDaThing()
{
return new Thing(this.arg1,...,this.argN);
}
}
however keep in mind that if the arguments are not of value type, then all your instances of Thing
will have references to the same objects, so, even though you have different instance of Things, they all would point to the same arg1. What you could do to fix that is to actually take in a Func in the parameter, so you can actually create a new one:
public MagicFactory
{
Func<T1> arg1, ,.., Func<TN> argN;
public MagicFactory(Func<T1> a1,..., Func<TN> aN)
{
this.arg1=a1;
...
this.argN = an;
}
public Thing GimmeDaThing()
{
return new Thing(this.arg1(),...,this.argN());
}
}
and you would call it like this:
var magicContainer = new MagicFactory(()=> new T1(...),..., ()=>new T2(..);
var thing1 = magicContainer.GimmeDaThing();
var thing1 = magicContainer.GimmeDaThing();
var thing1 = magicContainer.GimmeDaThing();
var thing1 = magicContainer.GimmeDaThing();
and you would get a fresh instance of Thing each time, each with their own property objects.