I have an asp.net-mvc site and I am using Unity to do dependency injection and all of my dependencies into controllers or model classes happen inside the constructor of the class.
My one issue now is that one class is expensive to instantiate and its only used in a single action inside my controller and thus I don't want to pass it into the constructor to be instantiated on every other action that is called on that controller. All examples i see on the web have dependencies being injected into the controller like this.
What is the correct way to deal with this situation where i only need a dependency for a single action. Right now I am just doing the "new" inside my constructor class which is something i want to avoid (as i haven't abstracted and decoupled the dependency implementation) but atleast i know it won't be a performance hit on any other action.
Creation of your application components should be fast and their constructors should be simple. Any heavy initialization should be postponed.
When this becomes impossible due to the existence of some legacy code, you should wrap the component behind a proxy implementation for the same interface. For instance:
public class LazyServiceProxy : IService
{
private readonly Lazy<IService> service;
public LazyServiceProxy(Lazy<IService> service) {
this.service = service;
}
void IService.Method(object param1) => this.service.Value.Method(param1);
}
Also note that the fact that your dependency is only used in a single action is an indication of low cohesion between the action methods of your controller. Low cohesion is a sign of a Single Responsibility Principle (SRP) violation. The SRP dictates that each class should have a single responsibility so this might meen it's good to move the action and its dependency to its own controller. While it is a common practice to group actions together based on their common url prefix (e.g. /customers/action
), MVC completely allows you to split actions into several controllers, while maintaining their original url.