Regarding the namings you have used, you create a misconfusion. Someone would expect a class named Foo
to implement the interface IFoo
and not inject an object that has implemented IFoo
in Foo
's constructor.
As far as the use of static method GenerateSomeFoo
, it makes the code less helpful to test it, since now you depend on a concrete implementation.
Another approach would be this:
// This is the contract.
public interface IFoo
{
void DoSomething();
}
// This is the implementation
public class Foo : IFoo
{
public void DoSomething()
{
// ....
}
}
If class Foo
needs another object to implement their methods, you could inject it in it's constructor. For instance let's suppose that it needs a IBarRepository
. Then the class Foo
would be declared as below:
public class Foo : IFoo
{
private readonly IBarRepository _barRepository;
public Foo(IBarRepository barRepository)
{
_barRepository = barRepository
?? throw new ArgumentNullException(nameof(fooRepository));
}
public void DoSomething()
{
// ....
}
}
Why the above approach is more preferrable ? Let's suppose that the definition of IBarRepository
is the following:
public interface IBarRepository
{
IEnumerable<Bar> GetAll();
}
and that a class that implements this interface makes a call to a database to retrieve Bar
objects. Using the interface as a dependency you can test your code quite easily using a mock of this interface, a thing that is not possible when you rely on static class or methods.