MVC Repository pattern - expensive instantiation, cheep static methods?
I use repository pattern in my MVC applicaton. Each repository contains data retreiving methods such as GetByID, GetByXXXX, GetByYYYY. If i need to execute methods like these from controllers of the other entities, i need to instantiate that repository just for that operation. Do you think this way is expensive for the system? Should I or not make these methods开发者_开发知识库 static? Thank you!
Instantiating a Repository isn't an expensive operation especially when measured against the normal round trip time of a web request. If the repository is read only, there is no problem in using a static instance but if it's read-write, you'll need a separate repository for each request.
You should not make them static. You should be using an IoC container to do dependency injection.
Here is an example with code: Entity Framework 4 CTP 4 / CTP 5 Generic Repository Pattern and Unit Testable
Post on useing IoC Containers: NuGet for Structuremap: http://nuget.org/List/Packages/StructureMap-MVC3
Blog post: http://www.bengtbe.com/blog/post/2009/02/27/Using-StructureMap-with-the-ASPNET-MVC-framework.aspx
Like we all say, I'd say "it depends.". Like Paul mentions in his answer, it's good to use Dependency Injection--but whether you do or not doesn't really have bearing on the core of your question.
I've put together several applications that do, but whether your code is using DI in the constructor
private ISomeInjectedType myRepository;
public SomeController(ISomeInjectedType type)
{
myRepository = type;
}
or just instantiating the type
private ISomeType myRepository;
public SomeController()
{
myRepository = new SomeType();
}
You'll essentially get the same result out of the code--leaving maintainability out of the argument.
I've done this via the DI approach for a number of applications, and have found zero drawbacks from a performance standpoint--even when inadvertently having a team get a little out of control and wind up injecting/creating about 12 "repositories" that were created for each controller constructor.
Either way, whatever works best for you. You mentioned you were getting started with MVC. My thoughts on that are yes, use DI, but do it when you're ready.
Take the small steps you need to in order to get things up and running, then advance them as needed.
Repository instantiation isn't performance costly operation, nor creation of ORM session is (be it NHibernate ISession or EF ObjectContext). Don't make unnecessary micro-optimisations and arm yourself with an IoC tool to easily and transparently inject all repository dependencies (it is much simpler than it seems before you use it first time).
Static methods are no way helpful here bacause you are not dealing with a static context (you should have a concrete instance of your ORM Session - and that is a state - you're not able to use it in a static context).
精彩评论