which is the unit of work and which is the repository? - repository-pattern

I have two interfaces and I'm confused about the naming conventions:
interface InterfaceA {
IDbSet<Patient> Patients { get; }
// others like above
}
interface InterfaceB : InterfaceA {
int Commit();
}
class DbContext : InterfaceB {
public IDbSet<Patient> Patients { get; set; }
int Commit() {
return this.SaveChanges();
}
}
I don't want to confuse the other coders on my team. Which interface is the unit of work and which one is the repository?

InterfaceA is the repository.
Reason:
A repository is responsible for persisting data, and InterfaceB has no concept of data to be persisted.

Related

Best practices of implementing unit of work and repository pattern using ServiceStack.ORMLite

Supposing that there are two repository interface :
interface IFooRepository
{
void Delete(int id);
}
interface IBarRepository
{
void Delete(int id);
}
And an IUnitOfWork interface like :
interface IUnitOfWork : IDisposable
{
void Commit();
void Rollback();
}
what is the best practices of implementing those interface using ServiceStack.ORMLite so that user can use them like
MyFooRepository.Delete(4);
// if an Exception throws here, Bar won't be deleted
MyBarRepository.Delete(7);
Or
using (var uow = CreateUnitOfWork())
{
MyFooRepository.Delete(4);
MyBarRepository.Delete(7);
uow.Commit(); //now they are in an transaction
}
Not sure of your need for Repository + UnitOfWork patterns but I think there are some alternative solutions in ServiceStack + OrmLite that keep your code 'DRY' before you need to introduce any patterns (especially if you're mainly seeking Transaction/Rollback support). Something like below is where I would start.
public class Foo //POCO for data access
{
//Add Attributes for Ormlite
public int Id { get; set; }
}
public class Bar //POCO for data access
{
//Add Attributes for Ormlite
public int Id { get; set; }
}
//your request class which is passed to your service
public class DeleteById
{
public int Id { get; set; }
}
public class FooBarService : MyServiceBase //MyServiceBase has resusable method for handling transactions.
{
public object Post(DeleteById request)
{
DbExec(dbConn =>
{
dbConn.DeleteById<Foo>(request.Id);
dbConn.DeleteById<Bar>(request.Id);
});
return null;
}
}
public class MyServiceBase : Service
{
public IDbConnectionFactory DbFactory { get; set; }
protected void DbExec(Action<IDbConnection> actions)
{
using (var dbConn = DbFactory.OpenDbConnection())
{
using (var trans = dbConn.OpenTransaction())
{
try
{
actions(dbConn);
trans.Commit();
}
catch (Exception ex)
{
trans.Rollback();
throw ex;
}
}
}
}
}
Some references...
https://github.com/ServiceStack/ServiceStack.RedisWebServices - The above code is modified from this example
https://groups.google.com/forum/#!msg/servicestack/1pA41E33QII/R-trWwzYgjEJ - discussion about layers in ServiceStack
http://ayende.com/blog/3955/repository-is-the-new-singleton - Ayende Rahien (NHibernate core contributor) on Repository pattern

How to decouple process in business layer

I am facing a problem that, for some business processes the sequence of invoking business objects and methods may change frequently. So I came up with something similar to the below:(Sorry somehow I can't post image..., I tried to express them in the below text)
Business Objects:
Object1, Object2
Methods: M1, M2, M3, M4
Processes: P1 (M1 > M2 > M3), P2 (M2 > M3 > if M3 return true then M4 else end)
In this case I am using .NET 3.5. I create some classes to represent processes, which contains those sequences I mentioned. It works. But the problem is I need to compile every time when process changed. It would be much better if I could configure it by some sort of XML.
I have heard about jBPM for Java, Workflow Foundation for .NET but not sure if they fit my needs, or would they be overkill. I even don't what keyword to search in Google. Could anyone advice what technology I should use to solve this issue? Or just point me to some websites or books? Thanks in advance.
A common way to decouple software layers is by using interfaces as stated by Dependency Inversion Principle. In you case you could abstract the process concept using an interface and implement the logic in the implementation of that interface.
when you need change the logic of the process you can create a new implementation of that interface. You can use any IoC framework to inject what implementation you want to use
below is showed just a simple way to do that:
public interface IMethod
{
void M1();
string M2();
void M3();
void M4();
}
public interface IProcess
{
IMethod Method { get; set; }
void P1();
void P2();
}
public class Process : IProcess
{
public IMethod Method
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public void P1()
{
Method.M1();
Method.M2();
}
public void P2()
{
if(Method.M2()==string.Empty)
{
Method.M3();
}
}
}
public class AnotherProcess : IProcess
{
public IMethod Method
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public void P1()
{
Method.M4();
}
public void P2()
{
Method.M2();
Method.M4();
}
}
public class UseProcess
{
private IProcess _process;
//you can inject the process dependency if you need use a different implementation
public UseProcess(IProcess process)
{
_process = process;
}
public void DoSomething()
{
_process.P1();
}
}

How to avoid casting between the DL - BL - UI layers ? (C#)

I designing an applications which basically has 3 different logic layers:
DB connector (implemented by ADO.NET).
BL the business logic (the only thing the UI knows).
DB repositories (connects between the first two).
The DB repositories are separated into sections of dependency and every final entity is polymorphic to one interface. In some cases there are dependencies between objects inside the same dependency sections - ISectionFactory (hence dependent).
In practice the BL is going to ask for an object of specific type (such as IngrediantType in my example) from the MainFactory (which is a factor for all the DB)
Because of this design I am forced to cast types on the UI - which obviously is a drag.
How can I change the design ?
Here is a brief look of design:
public class MainFactory
{
private Dictionary<Type, ISectionFactory> m_SectionsFactories;
private ISectionFactory treatmentsSectionFactory =
new TreatmentsSectionFactory();
public MainFactory()
{
m_SectionsFactories = new Dictionary<Type, ISectionFactory>
{
{typeof(IngrediantType),treatmentsSectionFactory}
};
}
public IConcreteDataCollection GetConcreteData(Type i_EntitiesName)
{
return m_SectionsFactories[i_EntitiesName]
.GetConcreteData(i_EntitiesName);
}
}
internal interface ISectionFactory
{
IConcreteDataCollection GetConcreteData(Type i_EntitiesName);
}
public class TreatmentsSectionFactory : ISectionFactory
{
private Dictionary<Type, IConcreteDataCollection>
m_ConcreteDataCollections;
private IngrediantTypes m_IngrediantTypes = new IngrediantTypes();
private Ingrediants m_Ingrediants = new Ingrediants();
public TreatmentsSectionFactory()
{
m_ConcreteDataCollections =
new Dictionary<Type, IConcreteDataCollection>();
m_ConcreteDataCollections
.Add(typeof(IngrediantType), m_IngrediantTypes);
m_ConcreteDataCollections
.Add(typeof(Ingrediants), m_Ingrediants);
}
public IConcreteDataCollection GetConcreteData(Type i_EntitiesName)
{
return m_ConcreteDataCollections[i_EntitiesName];
}
}
public interface IConcreteDataCollection : IEnumerable
{
// Iteratable.
IConcreteData GetById(int i_Id);
void AddNewConcreteData(IConcreteData i_ConcreteData);
void UppdateConcreteData(IConcreteData i_ConcreteData);
void DeleteConcreteData(IConcreteData i_ConcreteToDelete);
}
public class IngrediantTypes : IConcreteDataCollection
{
public string TestType { get; set; }
public IConcreteData GetById(int i_Id){}
public void AddNewConcreteData(IConcreteData i_ConcreteData){}
public void UppdateConcreteData(IConcreteData i_ConcreteData){}
public void DeleteConcreteData(IConcreteData i_ConcreteToDelete){}
public IEnumerator GetEnumerator(){}
}
// also implements IConcreteDataCollection
public class Ingrediants : IConcreteDataCollection
{
}
public interface IConcreteData
{
public int Index { set; get; }
} // the final (highest) entity of all DB entities
public class IngrediantType : IConcreteData
{
public int Index { set; get; }
// other set of properties
}
public class Ingrediant : IConcreteData
{
public int Index { set; get; }
public IngrediantType RelatedIngrediantType { set; get; }
// other set of properties
}
public class mainClass
{
public static void main()
{
MainFactory factory = new MainFactory();
var type = typeof(IngrediantType);
// returns a IngrdiantTypes of type (IConcreteDataCollection)
var t = factory.GetConcreteData(typeof(IngrediantType));
// I want to use the IngrediantType without casting !!!
var s = t.GetById(2);
}
}
It's a little hard to tell what's going on here, but I think the key will be to take advantage of generics like so:
public IConcreteDataCollection<T> GetConcreteData<T>()
{
return ...;
}
If I understand your question correctly, this will allow you to say:
var t = factory.GetConcreteData<IngrediantType>();
You will need to change almost every class in your code to use generics.

Cannot seem to moq EF CodeFirst 4.1.Help anyone?

I have been given the task to evaluate codeFirst and possible to use for all our future projects.
The evaluation is based on using codeFirst with an existing database.
Wondering if it's possible to mock the repository using codeFirst 4.1.(no fakes)
The idea is to inject a repository into a service and moq the repository.
I have been looking on the net but I have only found an example using fakes.I dont want to use fakes I want to use moq.
I think my problem is in the architecture of the DAL.(I would like to use unitOfWork etc.. by I need to show a working moq example)
Below is my attempt(Failed miserably) due to lack of knowledge on Code first 4.1.
I have also uploaded a solution just in case somebody is in good mood and would like to change it.
http://cid-9db5ae91a2948485.office.live.com/browse.aspx/Public%20Folder?uc=1
I am open to suggestions and total modification to my Dal.Ideally using Unity etc.. but I will worry about later.
Most importantly I need to be able to mock it. Without ability to use MOQ we will bin the project using EF 4.1
Failed attempt
//CodeFirst.Tests Project
[TestClass]
public class StudentTests
{
[TestMethod]
public void Should_be_able_to_verify_that_get_all_has_been_called()
{
//todo redo test once i can make a simple one work
//Arrange
var repository = new Mock<IStudentRepository>();
var expectedStudents = new List<Student>();
repository.Setup(x => x.GetAll()).Returns(expectedStudents);
//act
var studentService = new StudentService(repository.Object);
studentService.GetAll();
//assert
repository.Verify(x => x.GetAll(), Times.AtLeastOnce());
}
}
//CodeFirst.Common Project
public class Student
{
public int StudentId { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
}
public interface IStudentService
{
IEnumerable<Student> GetAll();
}
//CodeFirst.Service Project
public class StudentService:IStudentService
{
private IStudentRepository _studentRepository;
public StudentService()
{
}
public StudentService(IStudentRepository studentRepository)
{
_studentRepository = studentRepository;
}
public IEnumerable<Student> GetAll()
{
//TODO when mocking using moq this will actually call the db as we need a separate class.
using (var ctx = new SchoolContext("SchoolDB"))
{
_studentRepository = new StudentRepository(ctx);
var students = _studentRepository.GetAll().ToList();
return students;
}
}
}
//CodeFirst.Dal Project
public interface IRepository<T> where T : class
{
T GetOne(Expression<Func<T, bool>> predicate);
IEnumerable<T> GetAll();
IEnumerable<T> Find(Expression<Func<T, bool>> predicate);
void Add(T entity);
void Delete(T entity);
T Single(Func<T, bool> predicate);
T First(Func<T, bool> predicate);
}
public class RepositoryBase<T> : IRepository<T> where T : class
{
private readonly IDbSet<T> _dbSet;
public RepositoryBase(DbContext dbContext)
{
_dbSet = dbContext.Set<T>();
if (_dbSet == null) throw new InvalidOperationException("Cannot create dbSet ");
}
protected virtual IDbSet<T> Query
{
get { return _dbSet; }
}
public T GetOne(Expression<Func<T, bool>> predicate)
{
return Query.Where(predicate).FirstOrDefault();
}
public IEnumerable<T> GetAll()
{
return Query.ToArray();
}
public IEnumerable<T> Find(Expression<Func<T, bool>> predicate)
{
return Query.Where(predicate).ToArray();
}
public void Add(T entity)
{
_dbSet.Add(entity);
}
public void Delete(T entity)
{
_dbSet.Remove(entity);
}
public T Single(Func<T, bool> predicate)
{
return Query.Where(predicate).SingleOrDefault();
}
public T First(Func<T, bool> predicate)
{
return Query.Where(predicate).FirstOrDefault();
}
}
public class SchoolContext:DbContext
{
public SchoolContext(string connectionString):base(connectionString)
{
Database.SetInitializer<SchoolContext>(null);
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Not sure why I have to do this.Without this when using integration testing
//as opposed to UnitTests it does not work.
modelBuilder.Entity<Student>().ToTable("Student"); }
public DbSet<Student> Students { get; set; }
}
public interface IStudentRepository:IRepository<Student>
{
}
public class StudentRepository : RepositoryBase<Student>, IStudentRepository
{
public StudentRepository(DbContext dbContext)
: base(dbContext)
{
}
public IEnumerable<Student> GetStudents()
{
return GetAll();
}
}
Again feel free to modify or whatever is needed to help me to get something together.
Thanks a lot for your help
When I started with repository and unit of work patterns I used the implementation similar to this (it is for ObjectContext API but converting it to DbContext API is simple). We used that implementation with MOQ and Unity without any problems. By the time implementations of repository and unit of work have evolve as well as the approach of injecting. Later on we found that whole this approach has serious pitfalls but that was alredy discussed in other questions I referenced here (I highly recommend you to go through these links).
It is very surprising that you are evaluating the EFv4.1 with high emphasis on mocking and unit testing and in the same time you defined service method which is not unit-testable (with mocking) at all. The main problem of you service method is that you are not passing repository/context as dependency and because of that you can't mock it. The only way to test your service and don't use the real repository is using some very advanced approach = replacing mocking and MOQ with detouring (for example Moles framework).
First what you must do is replacing your service code with:
public class StudentService : IStudentService
{
private readonly IStudentRepository _studentRepository;
public StudentService(IStudentRepository studentRepository)
{
_studentRepository = studentRepository;
}
public IEnumerable<Student> GetAll()
{
return _studentRepository.GetAll().ToList();
}
}
Btw. this is absolutely useless code and example of silly layering which doesn't offer any useful functionality. Just wrapping the call to repository only shows that service is not needed at all as well as unit testing this method is not needed. The main point here is integration test for GetAll method.
Anyway if you want to unit thest such method with MOQ you will do:
[TestClass]
public class StudentsServiveTest
{
private Mock<IRespository<Student>> _repo;
[TestInitialize]
public void Init()
{
_repo = new Mock<IRepository<Student>>();
_repo.Setup(r => r.GetAll()).Returns(() => new Student[]
{
new Student { StudentId = 1, Name = "A", Surname = "B" },
new Student { StudentId = 2, Name = "B", Surname = "C" }
});
}
[TestMethod]
public void ShouldReturnAllStudents()
{
var service = new StudentsService(_repo.Object);
var data = service.GetAll();
_repo.Verify(r => r.GetAll(), Times.Once());
Assert.IsNotNull(data);
Assert.AreEqual(2, data.Count);
}
}
The issue from what I can see is that you are throwing away the mock object and newing up a new instance
_studentRepository = new StudentRepository(ctx);
Perhaps add a method on the interface to add the context object and reuse the same instance that was injected in the constructor.
using (var ctx = new SchoolContext("SchoolDB"))
{
_studentRepository.Context = ctx;
var students = _studentRepository.GetAll().ToList();
return students;
}
}

Unit Tests inheritance

How do i make Base class with [TestClass()], where i will do MyClassInitialize(), and after that, i will just make my another Test classes just like that - MyNewTest : BaseTest
and there will no initializing?
(using MSTest)
The ClassInitialize won’t work on a base class. It seems that this attribute is searched for only on the executed test class. However, you can call the base class explicitly.
Here is an example:
[TestClass]
public class MyTestClass : TestBase
{
[TestMethod]
public void MyTestMethod()
{
System.Diagnostics.Debug.WriteLine("MyTestMethod");
}
[ClassInitialize]
public new static void MyClassInitialize(TestContext context)
{
TestBase.MyClassInitialize(context);
}
}
[TestClass]
public abstract class TestBase
{
public TestContext TestContext { get; set; }
public static void MyClassInitialize(TestContext context)
{
System.Diagnostics.Debug.WriteLine("MyClassInitialize");
}
[AssemblyInitialize]
public static void AssemblyInit(TestContext context)
{
}
}
In NUnit/MbUnit you simply put the Initalize/Cleanup methods with the respective attributes in the base class, then inherit from it.
I haven't tried this yet with MSTest, but I wouldn't recommend this framework anyway.
Thomas