I have 2 constructor in my class:
public class CacheWebServices : ICacheWebService
{
public ICache apiConnector { get; set; }
public CacheWebServices(ICache ApiConnector)
{
apiConnector = ApiConnector;
}
public CacheWebServices()
: this(new VuelingCache())
{ }
}
As you can see, I have one constructor depending on IVuelingCache and a default constructor that creates an instance to pass to the first constructor. Is it correct? in this way i get rid of the Factory class.
Resolve dependencies using IServiceProvider You can use the IServiceCollection interface to create a dependency injection container. Once the container has been created, the IServiceCollection instance is composed into an IServiceProvider instance. You can use this instance to resolve services.
Don't use multiple constructors. Your classes should have a single definition of what dependencies it needs. That definition lies in the constructor and it should therefore only have 1 public constructor.
The class that needs the Dependency must expose a public constructor that takes an instance of the required Dependency as a constructor argument. This should be the only publicly available constructor. If more than one Dependency is needed, additional constructor arguments can be added to the same constructor.
This is one way to ensure that you have a valid instance of IVuelingCache
- this pattern has a name - poor man's dependency injection.
Some see this as an anti-pattern, as you are hard coding the "default" implementation into your code.
There is some debate as to that pattern being a good idea:
http://lostechies.com/chadmyers/2009/07/14/just-say-no-to-poor-man-s-dependency-injection/
In my opinion, if you have a good default that isn't a logically external dependency, then you should provide that default. If your "default" really shouldn't be a default, or would couple pieces that are too far from each other too strongly, then do not use that pattern.
You couple your code by doing this, so really think long and hard about whether it will be used as a convenience default for locally available default implementations, or if you're really just using this as a crutch, and causing inappropriately strong coupled dependencies.
Also, many people advocate using constructor injection only for required dependencies, and using property injection for optional dependencies. When you use the poor-man's DI pattern, you are making an optional (or defaultable) dependency. You might want to consider using property injection for these optional-dependency cases, as that is the pattern many people expect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With