Factories and entities

Current version: 10.2

The Factory Method Pattern is an object-oriented creational design pattern that implements the concept of factories. You can create objects without basing it on a specific class. The core of this pattern is to define an interface for creating an object, but let the classes that implement the interface decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses.

To configure the entity factory to use, set the type. By default, the Sitecore Factory is used implicitly through Connect:

<!-- ENTITY FACTORY Creates an entity by entity name. Allows to substitute default entity 
with extended one. -->
<entityFactory type="Sitecore.Commerce.Entities.EntityFactory, Sitecore.Commerce.Connect.Core" 
singleInstance="true" />

To configure custom objects in the Sitecore.Commerce.Carts.config file:

<!--  Connect ENTITIES Contains all the Connect entities. The configuration can be used to 
substitute the default entity implementation with extended one. -->
    <CartBase type="Sitecore.Commerce.Entities.Carts.CartBase, Sitecore.Commerce.Connect.Core" />
    <Cart type="Sitecore.Commerce.Entities.Carts.Cart, Sitecore.Commerce.Connect.Core" />

In an actual Connect provider implementation, the custom objects are known and do not necessarily have to be created through use of Factory.

You can use references to the factory as a parameter in some processors, for example, CreateCart:

<processor type="Sitecore.Commerce.Pipelines.Carts.CreateCart.CreateCart, Sitecore.Commerce.Connect.Core">
    <param ref="entityFactory" />

You must use the Factory.Create method to get an instance of the needed type. For example, in the following code snippet, we need a cart and call the factory to create and return a cart. The cart domain model can be completely modified and customized so that you can replace the default cart type with your own implementation:

public override void Process(ServicePipelineArgs args)
  var result = (CartResult)args.Result;
  var cart = this.entityFactory.Create<Cart>("Cart");
  var request = (CreateOrResumeCartRequest)args.Request;
  cart.UserId = request.UserId;
  cart.ShopName = request.ShopName;
  cart.CartName = request.CartName;
  cart.CustomerId = request.CustomerId;
  cart.CartStatus = CartStatus.InProcess;
  result.Cart = cart;

Do you have some feedback for us?

If you have suggestions for improving this article,