I have a factory that creates products. To do this I need an instance of some other class, that has nothing to do with the actual factory. However all Products should of course use the same instance of it, so I provided that instance to the factory which then passes it to every instance of the Product
:
public class MyFactory
{
Product CreateProduct(MyClass dependency)
{
return new Product(dependency);
}
}
public class Product
{
internal Product(MyClass dependency) { ... }
public void DoSomething() { /* use the dependency */ }
}
However it seems weird to me to provide something to my factory it doesn´t need at all but simply passes to its products.
The other alternative that comes to my mind is to provide the dependency where it´s actually needed, this is the DoSomething
-method within Product
. However this would enable users of my API to provide different instances of MyClass
to different products as shown here:
public class Product
{
public void DoSomething(MyClass dependency) { /* use the dependency */ }
}
...
var dependency1 = new MyClass();
var dependency2 = new MyClass();
myProduct.DoSomething(dependency1);
anotherProduct.DoSomething(dependency2);
The question therefore is: is it okay to provide a dependency to my factory that is actually a dependency for the actual Product
?
MyFactory
to create products with the sameMyClass
instance injected, thenMyFactory
actually also depends onMyClass
.