Repository pattern - Why exactly do we need Interfaces? - c#

I have read from internet I got this points which says Interfaces is used for this
Use TDD methods
Replace persistance engine
But I'm not able to understand how interface will be usefull to this point Replace persistance engine.
lets consider I'm creating a basic(without generics) repository for EmployeeRepository
public class EmployeeRepository
{
public employee[] GetAll()
{
//here I'll return from dbContext or ObjectContex class
}
}
So how interfaces come into picture?
and if suppose i created an interface why upcasting is used ? for e.g
IEmployee emp = new EmployeeRepository() ;
vs
EmployeeRepository emp = new EmployeeRepository();
Please explain me precisely and also other usefullness of Interface in regard to Repository Pattern.

So how interfaces come into picture ?
Like this:
public interface IEmployeeRepository
{
Employee[] GetAll();
}
and then you could have as many implementations as you like:
public class EmployeeRepositoryEF: IEmployeeRepository
{
public Employee[] GetAll()
{
//here you will return employees after querying your EF DbContext
}
}
public class EmployeeRepositoryXML: IEmployeeRepository
{
public Employee[] GetAll()
{
//here you will return employees after querying an XML file
}
}
public class EmployeeRepositoryWCF: IEmployeeRepository
{
public Employee[] GetAll()
{
//here you will return employees after querying some remote WCF service
}
}
and so on ... you could have as many implementation as you like
As you can see it's not really important how we implement the repository. What's important is that all repositories and implementations respect the defined contract (interface) and all posses a GetAll method returning a list of employees.
And then you will have a controller which uses this interface.
public class EmployeesController: Controller
{
private readonly IEmployeeRepository _repository;
public EmployeesController(IEmployeeRepository repository)
{
_repository = repository;
}
public ActionResult Index()
{
var employees = _repository.GetAll();
return View(employees);
}
}
See how the controller no longer depends on a specific implementation of the repository? All it needs to know is that this implementation respects the contract. Now all that you need to do is to configure your favorite dependency injection framework to use the implementation you wish.
Here's an example of how this is done with Ninject:
Install the Ninject.MVC3 NuGet
In the generated ~/App_Start/NinjectWebCommon.cs code you simply decide to use the EF implementation with a single line of code:
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IEmployeeRepository>().To<EmployeeRepositoryEF>();
}
This way you no longer need to do any manual instantiations of those repository classes and worry about upcasting or whatever. It is the dependency injection framework that manages them for you and will take care of injecting the defined implementation into the controller constructor.
And by simply modifying this configuration you could switch your data access technology without touching a single line of code in your controller. That's way unit testing in isolation also comes into play. Since your controller code is now weakly coupled to the repository (thanks to the interface we introduced) all you need to do in the unit test is to provide some mock implementation on the repository which allows you to define its behavior. This gives you the possibility to unit test the Index controller action without any dependency on a database or whatever. Complete isolation.
I also invite you to checkout the following articles about TDD and DI in ASP.NET MVC.

You would expose your repository as an interface:
public interface IEmployeeRepository
{
List<Employee> GetAll();
}
This would allow you to have many different implementations of the interface, such as the default one:
public class EmployeeRepository : IEmployeeRepository
{
public List<Employee> GetAll()
{
// Return from db.
}
}
Or a test one:
public class TestEmployeeRepository : IEmployeeRepository
{
public List<Employee> GetAll()
{
// Stub some dummy data.
}
}
Your code consuming the repository is then only interested in using the interface:
IEmployeeRepository myRepo = MyRepositoryFactory.Get<IEmployeeRepository>();
The secret sauce is the factory, or another mechanism by which to resolve the interface into a usable type (a Dependency Injection framework such as Ninject, or Castle Windsor will fulfil this role).
The point is, the consuming code doesn't care about the implementation, only the contract (the interface). This allows you to swap out implementations for testing purposes very easily and promotes loose coupling.
Just to clarify, there is no link between the use of interfaces and the repository pattern specifically, it is just another pattern that can make use of them.

Related

Create Restful Service Using Repository

I have a mvc application. I am using repository pattern and dependecy injection patterns. Here is a simple interface :
[ServiceContract]
public interface ICategoryService
{
[OperationContract]
List<Category> GetAll();
Category Add(Category category);
}
And a concrete class that implements this interface:
public class CategoryManager : ICategoryService
{
private readonly ICategoryDal _categoryDal;
public CategoryManager(ICategoryDal categoryDal)
{
_categoryDal = categoryDal;
}
public List<Category> GetAll()
{
return _categoryDal.GetWithSp();
}
public List<Category> GetAll(int a)
{
return _categoryDal.GetList();
}
public Category Add(Category category)
{
return _categoryDal.Add(category);
}
}
I inject this concrete class to interface in global.asax.
Now I need to create a web service to expose some methods in this interface (this interface just an example. Not only this one).
How can I do that with a few effort? Because most of this methods already works on web application, maybe just a few methods needs to be added.
Can I use this interaface as a contract, instead of creating a new one? Or what should I do when I also need to use another interface?
You can use it!
Enterprise level application architecture with web API's using Entity Framework, Generic Repository Pattern and Unit of Work.
using Web Api with generic repository

ASP.NET MVC 5 solution architecture improvement - multiple services with the same methods and code

I'm currently building an ASP.NET MVC 5 application using Unity and Entity Framework.
Here is my architecture (the solution contains multiple projects) :
Bootstrapper : project that contains the link between my interfaces and class for the repositories and the services
Data : mapping between my models and the database objects. This project contains the repositories as well.
Domain : this one contains the application constants + the interfaces of my repositories and services
Models : contains the models used in the application
Services : contains all the class Services
Web : the actual application with the views, controllers, view models, ...
Here is my issue: in multiple services I have the same methods (Get an item, check if it exists, ...) and these methods are exactly the same in every services except that they don't use the same repository and the same model.
Example :
public IQueryable<Car> Search(string search)
{
#region Sanitize parameters + Contracts
Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(search), Resources.Resources.SearchRequired);
search = StringHelper.SafePlainText(search);
Contract.Assume(search.Length <= 100 && search.Length > 1);
#endregion
return _carRepository.Search(StringHelper.SafePlainText(search));
}
I want to "extract" these methods so I don't have to recreate the same code over and over.
First, I thought about create an abstract class that my service inherit from but I couldn't figure out how to pass the right repository to the mother class.
This is what I tried :
public abstract class Service<T>
{
public object Repository { get; set; }
protected Service(object repository)
{
Repository = repository;
}
public IQueryable<T> Search(string search)
{
#region Sanitize parameters + Contracts
Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(search), Resources.Resources.SearchRequired);
search = StringHelper.SafePlainText(search);
Contract.Assume(search.Length <= 100 && search.Length > 1);
#endregion
return Repository.Search(StringHelper.SafePlainText(search));
}
}
But this, of course, doesn't work.
So I'm asking you guys if you have an idea to how I can manage to make this work, if this is possible at least.
Thank you in advance and excuse me for the poor language, I'm not an English native speaker.
Thibault.ce
First, you can inherits all your entity framework objects from a base class (optional) : http://fairwaytech.com/2013/09/using-a-common-base-class-across-entity-framework-database-first-entities/
Then, you can create a generic class "BaseRepository" which is based on the base class you created (or just "class"). This class will contains all generic methods. In this class, you can access the table corresponding to the base object using the entityframework method "Set()", which returns the DbSet of the typed pass in parameter.
After what you can inherit all your repositories from the "BaseRepository", and specify specific methods.
I made a simple example with 2 tables : https://dotnetfiddle.net/9hurx9
The best solution that I found is to create a generic class which depends of 2 types: The repository and the entity.
A BaseService< T1, T2 > which takes in parameter a "BaseRepository" and a "IEntity" and which will contain all the generic methods. This class must contain a property containing the instance of the repository. Thus, you can use the repository as shown in your example.
Then you can create specific Service classes, like a CarService which will inherit from BaseService< CarRepository, Car >.
A simple example, based on the example of my previous answer :
public class BaseService<TRepo, TEntity> where TRepo : BaseRepository<TEntity> where TEntity: IEntity
{
public TRepo Repository { get; set; }
public BaseService(TRepo repository)
{
this.Repository = repository;
}
public List<TEntity> GetAll()
{
return this.Repository.GetAll().ToList();
}
}
public class UserService : BaseService<UserRepository, User>
{
public UserService(UserRepository repository)
: base(repository)
{
}
public List<User> GetAllUserSortByName()
{
return this.Repository.GetAllUserSortByName();
}
}
You can use it like this :
YourEntities entities = new YourEntities();
UserRepository repo = new UserRepository(entities);
UserService service = new UserService(repo);
List<User> users = service.GetAllUserSortByName();
Let me know if my answer is not clear enough.
Edit :
Final example: https://dotnetfiddle.net/3s5BKZ
Thank you for you quick answer.
I managed to refactor my repositories and it's a really good point, thanks to your solution.
But at first my question was not about refactor my repositories but my services. I want to do the same process you did with the Entities.Set()... but with the call of my repositories.
Example:
I want to extract this method from my CarService :
public IQueryable<Car> GetAll()
{
return _carRepository.GetAll();
}
And put it in an abstract class Service. Something like :
public IQueryable<T> GetAll()
{
return Repository.GetAll();
}
But how to pass the right repository from the class CarService to the class Service ?
It's quiet hard to explain actually..
But thank you very much for the answer. It already helped me.

Design pattern for API entry point?

I'm creating a class library API that wraps business logic and access to an SQL Server database via Entity Framework 6.
I've designed it using the Unit of work and repository patterns.
The purpose is to make it easy to use and to unit test.
Business logic and validation will be performed in the service layer.
I will not use an IOC container because I feel that it would complicate the API
usage.
The project have 15 repositories and services
The current design is as follows:
Service Layer A -> Unit of work -> Repository A and or B
Service Layer B -> Unit of work -> Repository B and or A...
...
public class ServiceA : IServiceA, IService
{
private readonly IUnitOfWork unitOfWork;
public AssetService(IUnitOfWork unitOfWork)
{
this.unitOfWork = unitOfWork;
}
...
public IList<DomainObjectA> GetAll()
{
return unitOfWork.RepositoryA.GetAll();
}
public void Dispose()
{
unitOfWork.Dispose();
}
...
}
public class UnitOfWork : IUnitOfWork
{
private readonly MyDbContext context = new MyDbContext();
private IRepositoryA repositoryA;
private IRepositoryB repositoryB;
...
public IRepositoryA RepositoryA
{
get { return repositoryA = repositoryA ?? new RepositoryA(context); }
}
public IRepositoryB RepositoryB
{
get { return repositoryB = repositoryB ?? new RepositoryB(context); }
}
...
public void Save()
{
context.SaveChanges();
}
public void Dispose()
{
context.Dispose();
}
}
public class RepositoryA : Repository, IRepositoryA
{
public RepositoryA(MyDbContext context)
: base(context) {}
public IList<DomainObjectA> GetAll()
{
return context.tblA.ToList().Select(x => x.ToDomainObject()).ToList();
}
...
}
Since this is an API that should be used by other projects, I need a nice and "fairly" easy to use interface for the user that consumes the API.
Because of this the UnitOfWork is created in this "public interface" between the user and the service layer, see below.
I also think it's best that the using-statement lies within the API so that the db-context is disposed properly and immediately after each service call.
I started out using the Proxy pattern for this:
Example:
public class ProxyA : Proxy, IServiceA
{
public IList<DomainObjectA> GetAll()
{
using (var service = GetService<ServiceA>())
return service.GetAll();
}
...
}
public abstract class Proxy
{
protected T GetService<T>() where T : IService
{
return (T)Activator.CreateInstance(typeof(T), new object[] { new UnitOfWork()});
}
}
But this would require me to create a proxy for each service. I could of course skip the service interface in the proxy and create a common proxy which handles all the services.
I've also looked at the Facade pattern but can't decide which pattern to use for this particular scenario.
My questions:
Is this a good approach or are there any other design patterns that will solve this problem?
Also, should there be one public API entry point or several, grouped by some business logic?
I see nothing wrong with your design and the patterns you use.
Regarding the proxy pattern it is your call if you want to use it or not. As you mention you have to create boiler plate code to create one for every service. If it is arguable if you want to use it only to hide the call to the db service, or you prefer to add that line of code every time you call the service (and make sure you do it to avoid leaks). Also you may consider if you may need to add extra functionality in the Proxy in the future, which will put extra weight to create the proxy option.
Regarding a single entry point or several, I would create a ServiceA, ServiceB, ServiceC etc (so several) grouped for business logic domains. Typically you'll have between 5-20 (just an approximate number to give an idea of the magnitude)
You may want to review the interface segregation principle which supports this idea
http://en.wikipedia.org/wiki/Interface_segregation_principle

using UnitOfWork and Repository Pattern with Entity Framework

I'm gonna to use repository and UnitOfwork in my data access layer to do this take a look at one contact aggregateroot
public interface IAggregateRoot
{
}
this is my Generic repository interface :
public interface IRepository<T>
{
IEnumerable<T> GetAll();
T FindBy(params Object[] keyValues);
void Add(T entity);
void Update(T entity);
void Delete(T entity);
}
and my POCO Contact class in Model
public class Contact :IAggregateRoot
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Title { get; set; }
public string Body { get; set; }
public DateTime CreationTime { get; set; }
}
and this my IContactRepository that inherit from IRepository and also maybe has it is own method
public interface IContactRepository : IRepository<Contact>
{
}
Now I have done in IUitOfWork and UnitOfwork like this
public interface IUnitOfWork
{
IRepository<Contact> ContactRepository { get; }
}
public class UnitOfWork : IUnitOfWork
{
private readonly StatosContext _statosContext = new StatosContext();
private IRepository<Contact> _contactUsRepository;
public IRepository<Contact> ContactRepository
{
get { return _contactUsRepository ?? (_contactUsRepository = new Repository<Contact>(_statosContext)); }
}
}
also about my Repository
public class Repository<T> : IRepository<T> where T : class, IAggregateRoot
{
//implementing methods
}
I can do all CRUD operation with accessing Repositories with UnitOfwork in Service , example :
_unitOfWork.ContactRepository.Add(contact);
_unitOfWork.SaveChanges();
but I want to do like this
_
ContactRepository.Add(contact);
_unitOfWork.SaveChanges();
(get CRUD and generic method via _ContactRepository No by _unitOfWork.ContactRepository)
Because I want to get ContactRepository method to some specific queries ,
anybody help please ??
It's not a direct answer to your question, but it might simplify things a little bit and reduce duplication.
When you use e.g. EntityFramework Power Tools to reverse-engineer Code First (or just use Code First in general), you end up with the DbContext class that serves as a UoW and repository in one, e.g.:
public partial class YourDbContext : DbContext
{
public DbSet<Contact> Contacts {get; set;}
}
Now, if you want things to be testable, there's an easy way: introduce a very thin interface:
public interface IDbContext
{
IDbSet<T> EntitySet<T>() where T : class;
int SaveChanges();
//you can reveal more methods from the original DbContext, like `GetValidationErrors` method or whatever you really need.
}
then make another file with second part of the partial class:
public partial class YourDbContext : IDbContext
{
public IDbSet<T> EntitySet<T>() where T : class
{
return Set<T>();
}
}
Ta-da! Now you can inject IDbContext with YourDbContext backing it up:
//context is an injected IDbContext:
var contact = context.EntitySet<Contact>().Single(x => x.Id == 2);
contact.Name = "Updated name";
context.EntitySet<Contact>().Add(new Contact { Name = "Brand new" });
context.SaveChanges();
Now if you want to have control over the disposal of the context, then you'd have to write your own (gasp) IDbContextFactory (generic or not, depending what you need) and inject that factory instead.
No need to write your own Find, Add or Update methods now, DbContext will handle that appropriately, it's easier to introduce explicit transactions and everything is nicely hidden behind interfaces (IDbContext, IDbSet).
By the way, the IDbContextFactory would be an equivalent to NHibernate's ISessionFactory and IDbContext - ISession. I wish EF had this out of the box, too.
I agree with the Doctor, DbContext is already a UnitOfWork, and adding another UoW abstraction on top of it is typically redundant, unless you think it's highly likely you might switch database technologies in the future.
I don't agree, however, with treating DbSet's as repositories, since this tightly couples your queries to the methods that use them. If you need to change a query, you have to do it everywhere you use it.
I prefer to either use a stand-alone repository (or service interface, they serve similar functions) or to use more of a CQRS system for Command/Query Seperation, an use query objects.
Inside the UnitOfWork class you need to implement DBContext or ObjectContext.
UnitOfWork segregates all transactions regardless of the system. EF is only for DB connection. Even if your system is only using DB still it is better to keep a separate UnitOfWork class for future expansions.
And inside the unit of work Commit(), you can call the internally implemented DBContext.SaveChanges().
This DBcontext will be accessible to all repositories declared inside unitofwork. So repositories add or delete from DBcontext and unitOfwork commits it.
When you have scenarios spanning different storages eg: Cloud Blobs, table storage etc. You could implement them inside UnitofWork just like you implemented a EF context. And some repositories can access Table Storage and some EF context.
Tip: Implementing ObjectContext instead of DBContext gives you an edge in caching scenarios. And you have more options in extending your framework.

When and where todo dependency injection.Could you clarify?

Getting more and more familiar with DI but I still have few niggles.
Read few articles where it says "Injection must be done at the entry point"
Suppose I have a situation where we have wcf Services and these are used both by internal win/web application and external third parties uses those wcf services.
Now where do you inject the Services and repositories?
Above to me seems to be a common scenarios!
Also i pass all those interfaces around.(Very good for mocking) how do I stop somebody from calling EG my repository from a layer that should NOT be calling the repository.
EG only the business Layer should call DAL.
Now by injecting a IRepository into a controller nothing stops a developer from calling the DAL.
Any suggestion? Links that clear all this
Noddy example of my poor man DI. How do I do the same using unity and Injecting all at the entryPoint?
[TestFixture]
public class Class1
{
[Test]
public void GetAll_when_called_is_invoked()
{
var mockRepository = new Mock<ICustomerRepository>();
mockRepository.Setup(x => x.GetAll()).Verifiable();
new CustomerService(mockRepository.Object);
ICustomerBiz customerBiz = new CustomerBizImp(mockRepository.Object);
customerBiz.GetAll();
mockRepository.Verify(x=>x.GetAll(),Times.AtLeastOnce());
}
}
public class CustomerService : ICustomerService //For brevity (in real will be a wcf service)
{
private readonly ICustomerRepository _customerRepository;
public CustomerService(ICustomerRepository customerRepository)
{
_customerRepository = customerRepository;
}
public IEnumerable<Customer> GetAll()
{
return _customerRepository.GetAll();
}
}
public class CustomerBizImp : ICustomerBiz
{
private readonly ICustomerRepository _customerRepository;
public CustomerBizImp(ICustomerRepository customerRepository)
{
_customerRepository = customerRepository;
}
public IEnumerable<Customer> GetAll()
{
return _customerRepository.GetAll();
}
}
public class CustomerRepository : ICustomerRepository
{
public IEnumerable<Customer> GetAll()
{
throw new NotImplementedException();
}
}
public interface ICustomerRepository
{
IEnumerable<Customer> GetAll();
}
public interface ICustomerService
{
IEnumerable<Customer> GetAll();
}
public interface ICustomerBiz
{
IEnumerable<Customer> GetAll();
}
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
}
thanks
This is a blog post on Composition roots or what you call entry points. Its from Mark Seemann the author of Dependency Injection in .NET. If you are looking for a deep understanding of DI this book is a must read.
There are a lot of samples out there on how to combine WCF and DI. If you are hosting your services in IIS you would need to write a custom ServiceHostFactory where you initialize you DI container. This is a sample for Microsoft's Unity.
As to
how do I stop somebody from calling EG my repository from a layer that should NOT be calling the repository
Do you use poor man's DI and pass all your references around through all your layers? Then you should definitely consider using a DI/IoC container like StructureMap, Castle Windsor, AutoFac or Unity.
If you are asking "how can I in general avoid the situation that someone does not follow my layer boundaries": Write tests that fail if an assembly references another one it should not reference (e.g. UI should not reference DAL).
UPDATE
I assume you wanted the service to use ICustomerBiz instead of the ICustomerRepository. If that is right the setup for Unity would look like this:
[TestMethod]
public void GetAll_with_Unity()
{
var container = new UnityContainer();
container.RegisterType<ICustomerRepository, CustomerRepository>();
container.RegisterType<ICustomerBiz, CustomerBizImp>();
container.RegisterType<ICustomerService, CustomerService>();
var svc = container.Resolve<ICustomerService>();
var all = svc.GetAll();
Assert.AreEqual(1, all.Count());
}
DI is much more about injecting a dependency inside your dipendency architecture, that's why it can not resolve, as is, layers isolation problem you face.
Production code can and should contain DI code, if it needed.
If we are talking about plugin-based architectureDI is one of most natural choices out there.
if we are talking about app behaviour change, like for example Logging system choice: save on remote server if connection present if not injject local logger for future sync with the server.
There are plenty of usages of DI in production, but all that is up to Architect to decide when, how and if use it.
In other words, there is no single rule of it use, it's not a hummer for any nail, so use it where you think it's approriate and use it wisely.

Categories

Resources