Reputation: 12423
I'm working on a new webproject and I've encountered a problem which I never quite seems to figure out how to do correctly. My application is to use a repository that should be accessible from the entire application. Specifically it needs to be callable from ASP.NET MVC ActionFilters.
Any thoughts on the subject?
Upvotes: 0
Views: 76
Reputation: 84724
It looks like you are either looking for the singleton pattern or an Dependency Injection container (like Castle Windsor or Unity) configured with a singleton lifetime for the object.
In a singleton, you put a static "Instance" property accessor on the object and have it always return the same instance. Two things to note on the singleton pattern though:
Using a DI container, objects are constructed automatically with any dependencies (constructor arguments). Objects configured with a "singleton lifetime" will only every be constructed once and the instance shared with all objects that depend on it (beware threading issues).
// The repository argument will be resolved by the DI container
public ObjectConstructor(IRepositoryInterface repository)
{
this.repository = repository;
}
In the case of Attributes (like ActionFilters), where the class is constructed by the runtime, you would access the container (or an abstraction of it) directly and request your instance:
this.repository = Container.Instance.Resolve<IRepositoryInterface>();
Upvotes: 1