EF6 Repository pattern in Windows Service

The repository implements IDisposable and disposes the database context as you saw earlier in the controller, and its CRUD methods make calls to ...

EF6 Repository pattern in Windows Service

I'm not sure what you'd like to achieve exactly and what business requirements you have.

The structure is OK for now, but consider this: you have a user entity and a photo entity. Each user must have a photo associated with them. How would you handle that scenario?

You have to create a UserRepository and a PhotoRepository. Of couse you first have to insert the user record in order for the photo record to reference it later. So you call the Insert() method of the UserRepository. When the user is inserted, you call the Insert() method of the PhotoRepository. But what if that Insert() fails? Now you have a user in the db who doesn't have a photo.

You have to insert the user and the photo together, in one transaction. That's where the unit of work pattern comes in. You have to use that if you have business logic that concerns more than one entity type. If all you do is handle emails, then this is fine. If not, you have to add that pattern to your application. See an example here.

A service, again, is something that handles business transactions, and a business transaction can touch multiple types of entites. Again, the unit-of-work pattern can help you with this. But usually repositories are created based on your entites, and services based on your business logic. In the example, you could have a UserService that uses both the UserRepository and the PhotoRepository (usually through the unit of work).

In case of sending the e-mails, I would again design the services based on my business logic. And probably the business logic is to 'send e-mails', not to 'send e-mails via SMTP'. What happens if you decide to use a service like SendGrid? Then it is not SMTPService anymore.

I would probably create an EmailService (which you also have), and this would have a SendEmails() method. This would use the EmailRepository to fetch the emails, send it using SMTP, then update it and save it through the unit-of-work.

Or, if you want to be really abstract, you can create an IEmailSenderService interface with one method, SendEmail(Email email). Then you can create an SmtpEmailSenderService, which implements this interface and wraps the SmtpClient class and sends the email using SMTP. If you decide to move to SendGrid, you can create a SendGridEmailSenderService, that uses HttpClient to issue requests to SendGrid. The update is still done in the EmailService using the repository and the unit of work, but now the EmailService itself does not use SmtpClient but simply the IEmailSenderService interface.


Click Here to Visit

What's Your Reaction?

like
0
dislike
0
love
0
funny
0
angry
0
sad
0
wow
0