What is the correct way to create a new instance of a object using the repository pattern?
I've been playing around with the repository pattern using c# and .net.
my question regards creating new instances of someRepositoryObject
. All examples I've seen so far use something like this:
using(ISomeRepository someRepository = new SomeRepository().getRepository())
{
IsomeRepositoryObject repObj = new someRepositoryObject();
}
Doesn't calling new someRepositoryObject
remove the point of using interfaces in the first place? Would it better to do something like:
using(ISomeRepository someRepository = new SomeRepository().getRepository())
{
IsomeRepositoryObject repObj = someRepository.NewsomeRepositoryObject();
}
So the rep开发者_如何转开发ository itself returns a new instance of the required object and the calling code has no knowledge of the class being passed to it, just that it is of type ISomeRepositoryObject
.
This is all new to me, so I might be missing something obvious!
Any help would be appreciated.
Usually I'm using the second way you described and let the repository create a new instance. The reason is - as you mentioned, too - that I'm trying to separate the implementations of the interfaces from the code that uses the repository.
I would use IOC Containers to help.
Ninject is a nice solution to this. For example, in my MVC program, all my controller need some Service:
public class SampleController: Controller {
public SampleController(IService service) {}
}
the IService is injected by Ninject, only global.asax.cs need to acknowledge the concrete class.
What you have just described is abstract factory pattern. In case of repository it's better to use IoC container to create new objects. In this case you will not use new keyword at all and you will work with abstraction only. Repository by Martin Fowler
精彩评论