Ehsan Ghanbari

Experience, DotNet, Solutions

Does it cause any kind of performance issue using a base class in Layer SuperType pattern?

I had a long discussion with one of my colleague about using a base class in Data access layer or repository instead of implementing all common scenario like CRUD operation for every aggregate. it's Layer SuperType pattern that I'm talking about. I've posted about Layer SuperType pattern before, but now I'm going to know that what will happen in an application with large amounts of requests and transactions to performance in the case of using a base class for Common methods of DAL.

This this the answer of Scott Millet on Twitter for my question, here is the discussion 

 

          LayerSupertype

As you can see in the StackOverflow link suggested by Scott here, when you inherit from a base class and construct an object, the runtime never separate instances of the base class from inherited class. In other words, it's not like that you have two objects in memory when you have the variables of a base class in inherited class. When you inherit from a base class you have all variable of the base class and runs the base class constructor and also Both abstract and normal base classes act the same.  So it's not like that when you have an Insert method for a large application with lots request, you are using just the same insert to cause a performance problem!

 



Domain driven design VS model driven architecture

Domain Driven design(DDDesign) is not the same Model Driven Architecture(MDA). Although The root of both DDDesign and MDA is the same and it is Model Driven Engineering and also both of them aim to solve the problem of converting a 'pure' problem domain model into a full software system. But there are some differences.

Domain Driven Design concentrates on Modeling and solving the Domain problem by Capturing the model from the Ubiquitous language. it is about modeling a domain of knowledge with a high level of abstraction and its focuses are on domain logic and tries to keep the design as much close to the real world. In DDDesign you create the model with the Ubiquitous language so you should understand the business without any technical issues. In another side, model forms the ubiquitous language of DDDesign which explains the domain in a simple form and it's kinda a backbone of DDDesign.

But Model-driven architecture is an approach to building the model of the system. As I mentioned MDA is a kind of domain engineering too. A model is just some taken classes, methods and ... from the problem domain. MDA provides you to use multiple standards such as UML. 

 

but you know it doesn't stop there, I don't know more than these two paragraphs about differences of DDD and MDA! please let me know more about these two architectures and differences by comments, thanks...



Apply to request response pattern in your service layer

Messaging pattern is one of my favorite patterns to use in the service layer! since I've read Pro Asp.net Design pattern by ScottMillett I've been a big fan of patterns and how to apply them, in this article I'm going to talk about request-response pattern.

"Design patterns that are associated in the realm of large-scale distributed applications like SOA systems are often referred to as Messaging patterns. Messaging patterns, like Design patterns, provide standard solutions to complex problems. Messaging patterns tackle the sharing of data in a uniform manner among many disconnected systems." ~@ScottMillett

So let's implement it, I'm going to define the News part of a project that I'm tackling with at the moment, I will just implement two operations, I have defined these methods in INewsService :

CreateNews , GetNews , GetAllNews , UpdateNews , RemoveNews , GetNewsByDate , GetAllArchivedNewsByDate

And I'm discussing CreateNews and GetAllArchivedNewsByDate .So For each of them, I should create a response and a request class. let's begin by creating the messaging classes

 

    public class CreateNewsResponse
    {
       public NewsViewModel PostViewModel { get; set; }
    }

 

This response class that returns a property of NewsViewModel type lets me access the NewsViewModel properties.  and about CreateNewsRequest I usually create a constructor contained newsViewModel as a parameter to make it using the method in service implementation and also Presentation simple

 

    public class CreateNewsRequest
    {
        internal NewsViewModel NewsViewModel { get; private set; }
        public CreateNewsRequest(NewsViewModel newsViewModel)
        {
            NewsViewModel = newsViewModel;
        }
    }

 

Now in INewsService interface, define the CreateNews like this

 

    public interface INewsService
    {
             CreateNewsResponse CreateNews(CreateNewsRequest request);
    }

 

As you can see CreateNews contains a response as an output and a request as a parameter. And as I promised, I Create messaging classes of GetAllArchivedNewsByDate :

 

    public class GetAllNewsRequest
    {
        internal NewsViewModel NewsViewModel { get; private set; }
        internal int Year { get; private set; }
        internal int Month { get; private set; }
       
        public GetAllNewsRequest(NewsViewModel newsViewModel)
        {
            NewsViewModel = newsViewModel;
        }
        public GetAllNewsRequest(int year, int month)
        {
            Year = year;
            Month = month;
        }
    }

 

As you see in the request class I've defined two constructors, first one is the same you saw in CreateNewsRequest and the second one take two parameters (year and month) because I need this constructor in presentation layer that you will see later!

And about response class

 

    public class GetAllNewsResponse
    {
        public IEnumerable<NewsViewModel> PostViewModels { get; set; }
    }

 

It returns an IEnumerable of NewsViewModel cause it maybe has more than one news in a date.

And then in INewsService I have to define the GetAllArchivedNewsByDate like this :

 

    public interface INewsService
    {
             CreateNewsResponse CreateNews(CreateNewsRequest request);
             GetAllNewsResponse GetAllArchivedNewsByDate(GetAllNewsRequest request);
    }

 

Well, about implementing these methods in NewsService take a closer look at NewsService :

 

    public class NewsService : INewsService
    {
        private readonly INewsRepository _newsPostRepository;
        private readonly IUnitOfWork _unitOfWork;
        public NewsService(INewsRepository newsPostRepository , IUnitOfWork unitOfWork)
        {
            _newsPostRepository = newsPostRepository;
            _unitOfWork = unitOfWork;
        }
        public CreateNewsResponse CreateNews(CreateNewsRequest request)
        {
            var response = new CreateNewsResponse();
            var newsPost = request.NewsViewModel.ConvertToNewsPostModel();
            newsPost.CreationTime = DateTime.Now;
            newsPost.NewsSlug = request.NewsViewModel.Title.GenerateSlug();
            _newsPostRepository.Add(newsPost);
             _unitOfWork.SaveChanges();
            return response;
        } 
        public GetAllNewsResponse GetAllArchivedNewsByDate(GetAllNewsRequest request)
        {
            var response = new GetAllNewsResponse();
            var newses = _newsPostRepository.GetAllArchivedNewsByDateQuery(request.Year, request.Month);
            response.PostViewModels = newses.ConvertToNewsViewModelList();
            return response;
        }

 

Notice about GetAllArchivedNewsByDateQuery method, it's defined in the Repository layer and it returns a value by Query Object pattern from the database.

And about ConvertToNewsViewModelList and ConvertToNewsPostModel I've talked about before in the Automapper article, I use the extension method to convert objects to each other.

So if you are solicitous about how to use these service in the presentation layer, take a look again! I'm using MVC4 in UI, here is what I've done in the controller :

 

    public class NewsController : BaseController
    {
        private readonly INewsService _newsService;
        public NewsController(ICookieStorageService cookieStorageService, INewsService newsService)
            : base(cookieStorageService)
        {
            _newsService = newsService;
        }
       public ActionResult Create()
        {
            return View("Create");
        }
        [HttpPost]
        public ActionResult Create(NewsViewModel newsViewModel)
        {
            var createNewsRequest = new CreateNewsRequest(newsViewModel);
            if (ModelState.IsValid)
            {
                _newsService.CreateNews(createNewsRequest);
                 return View("Create");
            }
            return View("Create");
        }
        public ActionResult Archive(int year, int month)
        {
            var request = new GetAllNewsRequest(year, month);
            var newses = _newsService.GetAllArchivedNewsByDate(request);
            return View("Archive", newses.PostViewModels);
        }
   }

 

As you can see in Archive ActionResult  I just used the second constructor of GetAllNewsRequest and also can use any constructor if I need! Thanks for reading this and have a good time...



Difference between Anemic Domain Model and Rich domain model

There are lots of differences between these to approach. Anemic model is an anti-pattern introduced by Martin Fowler to encourage developers to duplicate code!  Based on the main idea behind DDD, if you have ubiquitous language then you can have domain model Anemic domain model is the use of a software domain model where the domain objects contain little or no business logic. in a Rich Domain, a Model behavior is included in the domain object while in Anemic Domain Model behavior is implemented in separate classes.

At some point in the design of the software, it is decided to implement certain pieces of logic for a domain entity outside of that domain entity.  This may be as a result of an explicit design decision or some pieces of logic just cannot be implemented in the domain entity because it is a persistent class and has no internal references to external services. 

The fundamental horror anemic model is that it's so contrary to the basic idea of object-oriented designing; which is to combine data and process them together. anemic objects are not real objects, and it's something different from object-oriented design. In the anemic model, business logic is typically implemented in separate classes which transform the state of the domain objects. "A domain model in problem-solving and of all the topics related to a certain problem. It describes the various entities, their attributes, roles, and relationships, plus the constraints that govern the problem domain. The domain model is created in order to represent the vocabulary and key concepts of the domain problem." ~ Wikipedia



Repository Pattern practice in data access layer via entity framework

To read about definitions of Repository pattern refer to here or here and then let's begin! I'm gonna to show the using of repository pattern with entity framework in Data access layer. Sorry about the example because it's about product, category, brand, blah blah again! First of all, create an interface called IAggregateRoot

 

   public interface IAggregateRoot
    {
    }

 

It has no any member, you will find out what's that for later in this article, then create a generic type interface for introducing the most common operation used in enterprise DAL such as CRUD …

 

 public interface IRepository<T>
    {
        IEnumerable<T> GetAll();
        T FindBy(params Object[] keyValues);
        void Add(T entity);
        void Update(T entity);
        void Delete(T entity);
        void SaveChanges();
    }

 

Now create the Product class and derive it from or so-called implement the IAggregateRoot member for it!

 

    public class Product : IAggregateRoot
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
        public string Description { get; set; }
        public DateTime CreationTime { get; set; }
        public string Picture { get; set; }
    }

 

And now create the IProductRepository interface like this :

 

    public interface IProductRepository : IRepository<Product>
    {
    }

 

I have to notice that all we have done above are in the Model layer if you are using layered application, now refer to your DAL or Repository layer and create your DbContextClass:

 

   public class YourProjectContext : DbContext
    {
          public DbSet<Product> Product { get; set; }
    }

 

And now create the GenericRepoitory class like this :

 

    public class Repository<T> : IRepository<T> where T : class, IAggregateRoot
    {
        private readonly DbSet<T> _entitySet;
        private readonly YourProjectContext _yourProjectContext ;
        public Repository(YourProjectContext yourProjectContext )
        {
            _yourProjectContext = yourProjectContext ;
            _entitySet = yourProjectContext .Set<T>();
        }
        public IEnumerable<T> GetAll()
        {
            return _entitySet;
        }
        public T FindBy(params Object[] keyValues)
        {
            return _entitySet.Find(keyValues);
        }
        public void Add(T entity)
        {
            _entitySet.Add(entity);
        }
        public void Update(T entity)
        {
            _entitySet.Attach(entity);
           _yourProjectContext.Entry(entity).State=EntityState.Modified;
        }
        public void Delete(T entity)
        {
            var e = _yourProjectContext.Entry(entity);
            if (e.State == EntityState.Detached)
            {
                _yourProjectContext.Set<T>().Attach(entity);
                e = _yourProjectContext.Entry(entity);
            }
            e.State=EntityState.Deleted;   
        }
        public void SaveChanges()
        {
            _yourProjectContext.SaveChanges();
        }
    }

 

 you have all members of IRepository<T> implemented in this class, Now create the ProductRepository class like this :

 

    public class ProductRepository :Repository<Product>,IProductRepository
    {
      public ProductRepository(YourProjectContext yourProjectContext)
            : base(yourProjectContext)
        {
        }
    }

 

Now by calling IProductRepository interface in service or application layer, you have full access to the whole generic method of Repository and also for all members of ProductRepository, for example, spouse this service class

 

    public class ProductService : IProductService
    {
        private readonly IProductRepository _productRepository;
        public ProductService(IProductRepository productRepository)
        {
            _productRepository = productRepository;
        }
     }

 

You can access the repository members by _productRepository read-only field. I want to create a specific method in ProductRepository such as FindAllProductsByCategory  you have to first define it in IProductRepository :

 

    public interface IProductRepository : IRepository<Product>
    {
        IEnumerable<Product> FindAllProductsByCategory(Guid categoryId);
    }

 

And Then in ProductRepository, you have to implement the interface member

 

    public class ProductRepository :Repository<Product>,IProductRepository
    {
        private readonly StatosContext _statosContext;
        public ProductRepository(StatosContext statosContext)
            : base(statosContext)
        {
            _statosContext = statosContext;
        }
        public IEnumerable<Product> FindAllProductsByCategory(Guid categoryId)
        {
            var query =
                _statosContext.Product.Where(p => p.Category.Id == categoryId).OrderByDescending(p => p.CreationTime);
            return query.ToList();
        }

 

Thanks for reading!

Question!  is there any need to use the unit of work pattern when you using repository pattern with entity framework ??

Basically NOT because entity framework supports the UnitOfWork pattern and in other words, entity framework code first has been built based on UnitOfwork pattern and adding unitOfWork again is  typically redundant (because of using DbContext), but if want to have more control over disposal of context you can write your own IDbContextFactory and implement the unit of work pattern ! Cheers



About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns and I'm spending a lot of my time on architecture subject. Since 2008, I've been as a developer for companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the&nb Read More

Post Tags
Pending Blog Posts
Strategic design
Factory Pattern
time out pattern in ajax
Selectors in Jquery
Peridic pattern
How to query over Icollection<> of a type with linq
How to use PagedList In asp.net MVC
Domain driven design VS model driven architecture
What's the DDD-lite?
Using Generic type for type casting in F#