I have a WCF service that has a few different responsibilities, but it provides one entry point for anyone interacting with my code. To keep it simple, let's say there are 2 methods
private IMethodAHelper _methodA;
private IMethodBHelper _methodB;
public MyService(IMethodAHelper methodA, IMethodBHelper methodB)
{
_methodA = methodA;
_methodB = methodB;
}
public void MethodA() {
_methodA.CallThis();
}
public void MethodB() {
_methodB.CallThis();
}
Because consumers will only call the service for one reason, MethodA or MethodB, is it a problem that the IOC container will be needlessly spinning up all dependencies? I want to provide a single entry point, so I don't want to split up the service, but it seems a little wasteful to spin up all the dependencies when each consumer of the service will only need a subset.
Another way I was thinking of doing this would be something like
public void MethodA() {
var methodA = ObjectFactory.GetInstance<IMethodAHelper>();
methodA.CallThis();
}
This allows each "path" to bring up the dependencies it needs, however, that makes it a lot harder to write unit tests. Does anyone have any suggestions? How big of an issue is it to spin up all the dependencies? After this first entry point into the service, it will make sense to inject the dependencies via the constructor, but at this first entry point, what is the recommended approach?
You should stick with Constructor Injection and not worry about the construction overhead. It's very rarely an issue, and if it is, there are elegant ways to deal with it.
As Mark sais you should not worry about creating dependencies that are not used unless you have some actual prof (times from profiler) that they are expensive to create. If you have some expensive to create components you might want to use a container that supports lazy injection like AutoFac. That way you can have Lazy injected which will be constructed only on first use.
A general rule of thumb for dependency injection is, that all (required) dependencies that a class needs to work properly should be injected via constructor injection.
All (optional) dependencies should be injected via property injection. Optional in this case is, when the class provides a default implementation of an interface and you want to change the interface implementation on run- or configuration time.
Anyway i agree with Mark Seemann´s answer.
I don't know the details of what you are doing, but it may make more sense to break them out into separate services.
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