Reputation: 867
I've implemented the repository pattern. I've got my base model classes, which are nothing more than standard C# classes. I've got my repository classes for each model. I've got my DbContext
class. I'm using Ninject, so everything, except for my models, are first defined as interfaces. Right now, to access my data, my code looks like this:
using (var context = m_kernel.Get<IPortalContext>())
{
var accounts = m_kernel.Get<IAccountRepository>(new ConstructorArgument("context", context));
foreach (var account in accounts.All())
{
Assert.IsNotNull(account);
}
}
Note: I'm not sure if there's a better way to say that I want to pass that context into the IAccountRepository constructor, but that's for another time.
As you can see, my repository classes all require a context instance. This is so I work on the same context, for like a unit of work.
My question is, how can I introduce a service layer for my business logic? Right now, my repositories just have simple Get, Delete, All, Insert methods. I want a service layer for my specific business logic and validation. What's the best way to go about this?
At first glance, I could just make service classes, much like my repo classes, that take in the context and perform the business logic and then use the repo class. That'd basically hide the repositories all together.
Is this a good approach?
Upvotes: 1
Views: 96
Reputation: 7491
That is the approach I use. That also would allow you to make your Repositories generic. Here is an example:
Internal class AccountService
{
Public Account GetAccount(string firstName)
{
var results = Enumerable.Empty<Account>();
try
{
var repository = new Repository<Account>(); // I use and interface here and
// then a factory class. I just
// was trying to keep it simple.
results = repository.FindAll()
.Where(a => a.FirstName == firstName)
.ToList();
}
catch()... etc.
return results;
}
}
Public interface IAccountService
{
Account GetAccount(string accountNumber);
}
By using this pattern it allows you to mock the results of your repository classes and unit test your Service class methods and then because you are using an interface for your service class you can mock the results of your Service methods when needed if you are unit testing your UI level...
Also I have successfully created generic repository classes for LinqToSql and EntityFramework so I can change frameworks and the rest of the application doesn't care.
Upvotes: 1