简体   繁体   中英

MVC Onion architecture, some questions

I'm creating a project with Asp.net MVC 5, Web Api 2, and Entity Framework. I'm designing it with an Onion architecture, so I have a DAL, Service and UI layers.

My DAL layer contains a UnitOfWork and Repositories, my Service layer contains services for business cases.

But I have the following questions:

  1. Where do I use unit of work save (or commit) method?, in Services layer or in UI layer? if I use it in Services layer how do I deal with cases that span multiple Services?

  2. I'm using DTOs for webapi operations, should the Services layer return DTOs or the mapping should be done in the UI layer?

  3. Should DTOs be in a separate project or in the UI project? If they are in a separate project should I use MVC attributes for validation?

Your unit of work should exist in your service layer. Each call to the service contains a business transaction inside a single unit of work.

    public ServiceResponse<Patient> Save(Patient patient, string userName)
    {
        Func<Patient> func = delegate
        {
            Authorize(patient, userName);
            Validate(patient, new PatientValidator());

            using (var context = _contextFactory())
            {
                return context.Save(patient, userName);
            }
        };
        return this.Execute(func);
    }

The services layer should return your business entities, any mapping for the purpose of network communication/json formatting should be done in web api. This allows maximum reuse of your services.

If by DTO's you are referring to the objects you use for across the wire/json serialization, then they should stay in the same project as the Web Api. That may or may not be the same project where you have your UI. If your using Web Api, I recommend using a validation library like FluentValidation.

An example of Onion architecture https://github.com/carbonrobot/FullStackEF using C#, EF, Web Api

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM