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
Related
I want to verify if I'm doing the right thing and how to do DI for the parameterized constructor.
1. Created a interface to get DBContext
public interface IDBFactory
{
DynamoDBContext GetDynamoDBContext();
DynamoDBContext GetDynamoDBContext(DynamoDBContextConfig config);
}
2. Created a class to get AWS profile by implementing IDBFactory
public class DBFactory : IDBFactory
{
public DBFactory(string awsProfile)
{
var sharedFile = new SharedCredentialsFile();
sharedFile.TryGetProfile(awsProfile, out var profile);
AWSCredentialsFactory.TryGetAWSCredentials(profile, sharedFile, out var credentials);
amazonDynamoDBClient = new AmazonDynamoDBClient(credentials, profile.Region);
}
public DynamoDBContext GetDynamoDBContext()
{
DynamoDBContext context = new DynamoDBContext(amazonDynamoDBClient);
return context;
}
}
3. Created a generic interface
public interface IGenericDbContext<T> : IDisposable where T : class
{
Task<T> GetByIdAsync(string id);
Task SaveAsync(T item);
Task DeleteByIdAsync(T item);
}
4. Created a class extending the interface
public class GenericDbContext<T> : IGenericDbContext<T>
where T : class
{
public GenericDbContext(IDBFactory DBFactory, DynamoDBContextConfig config = null)
{
}
/// Implementation of methods using DynamoDB SDK
}
So the first question is, Am I correct till now with the architecture?
Now all this code will go under a nuget package.
So I have to create another repository and install the nuget package so my new repository should be again generic, and I'm not sure how to do this, I tried this one, but it seems incorrect and duplicated.
public interface IStore<T> : IGenericDbContext<T> where T : class
What is the correct way to have another repository layer which is generic, please note that the nuget package that I created is distributable and I have to consume that in my repository layer.
Apart from that I'm not able to do dependency injection for the parameterized constructor,
I tried below, but it fails.
services.AddScoped<IDBFactory>(provider => new DBFactory("default"));
services.AddScoped(typeof(IGenericDbContext<>), typeof(GenericDbContext<>))
Please help me with the architecture and my DI failing logic for the parameterized constructor.
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.
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
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.
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.