开发者

Application-wide repository

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 c开发者_JS百科allable from ASP.NET MVC ActionFilters.

Any thoughts on the subject?


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:

  1. There are threading issues, which are covered by the MSDN doc on singletons
  2. It is generally considered an anti-pattern as it promoted class coupling

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>();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜